java - I would like to add (insert) column numbers (from 1 to 1000) at first column in the .CSV file -
for example
my input.csv contains data this..
row_no ,user , actions
john , sql transaction
suman , transaction failed
ram , button pressed retrieve details
and looking for.. advance each 1 of have tried this
output.csv
row_no ,user , actions
1 ,john , sql transaction
2 ,suman , transaction failed
3 ,ram , button pressed retrieve details
please me
this have tried
public class mapwriter { public static void main(string[] args) throws ioexception { csvmapreader mapreader = null; icsvmapwriter mapwriter = null; try { csvpreference prefs = csvpreference.standard_preference; mapreader = new csvmapreader(new filereader("d:\\input.csv"), prefs); mapwriter = new csvmapwriter(new filewriter("d:\\output.csv"), prefs); // header used read original file final string[] readheader = mapreader.getheader(true); // header used write new file // (same 'readheader', additional column) final string[] writeheader = new string[readheader.length + 1]; system.arraycopy(readheader, 0, writeheader, 0, readheader.length); final string timeheader = " "; writeheader[writeheader.length-1]= timeheader; mapwriter.writeheader(writeheader); int count=1; map<string, string> row; while( (row = mapreader.read(readheader)) != null ) { // add column desired value row.put(timeheader, string.valueof(count)); mapwriter.write(row, writeheader); count++; } } { if( mapreader != null ) { mapreader.close(); } if( mapwriter != null ) { mapwriter.close(); } } }
}
as far can tell, you're trying use verifying csv parser on invalid data (e.g. row_no blank everywhere header in input file). i'm not if that's allowed parser, don't believe need parse file yet. example, stringtokenizer , scanner -
public static void main(string[] args) { string inputfile = "c:/input.csv"; string outputfile = "c:/output.csv"; int linenumber = 0; // <-- keep line count. scanner scanner = null; printwriter pw = null; try { pw = new printwriter(outputfile); // <-- output file source = new file(inputfile); scanner = new scanner(source); // <-- input while (scanner.hasnextline()) { string line = scanner.nextline(); line = (line != null) ? line.trim() : ""; if (line.length() < 1) { continue; } // line 0 header. if (linenumber != 0) { pw.print(linenumber); pw.print(", "); } int tokencount = 0; stringtokenizer st = new stringtokenizer(line, ","); while (st.hasmoretokens()) { string token = st.nexttoken(); if (tokencount != 0) { pw.print(", "); } pw.print(token.trim()); tokencount++; } pw.println(); linenumber++; } } catch (filenotfoundexception e) { e.printstacktrace(); } { if (scanner != null) { scanner.close(); } if (pw != null) { pw.close(); } } }
after running above, generated output.csv
(based on input.csv
) -
row_no, user, actions 1, john, sql transaction 2, suman, transaction failed 3, ram, button pressed retrieve details
Comments
Post a Comment