2

I admit I am not a great Java programmer and probably my question is pretty dumb.I need to add new columns in different places to an existing csv file. I'm using the super-csv library.

My input file is something like that

1,2011-5-14 16:30:0.250,A
2,2011-5-14 16:30:21.500,B
3,2011-5-14 16:30:27.000,C
4,2011-5-14 16:30:29.750,B
5,2011-5-14 16:30:34.500,F

AS you can see, i have (or need) no header. And I need to add a column in column(2) and a column at the end of each row in order to get:

1,1,2011-5-14 16:30:0.250,A,1
2,1,2011-5-14 16:30:21.500,B,1
3,1,2011-5-14 16:30:27.000,C,1
4,1,2011-5-14 16:30:29.750,B,1
5,1,2011-5-14 16:30:34.500,F,1

From the library documentation i got (am i wrong?) that I cannot directly modify the original file, but the best idea is to read it and write it back. I guess using CsvMapReader and CsvMapwriter could be a good choice. But how can I add the columns in between existing ones? I should read each field of the existing column separately, and I tried to find suggestions in the library documentation but i cannot understand how to do it.

Any
  • 75
  • 2
  • 9
  • Hi, this was answered on the [Super CSV discussion board](http://sourceforge.net/p/supercsv/discussion/718795/thread/8af1bf14/#d465). Michal's answer is similar, though this one uses CsvMapReader/Writer - which _does_ require the use of a header (either read from the file, or supplied programatically) for mapping. – James Bassett Jan 22 '14 at 21:46
  • Also related to http://stackoverflow.com/q/11035602/1068649 – James Bassett Jan 22 '14 at 21:47
  • Thank you both! @HoundDog, i read that but i do not have a header in my files, nor can i add it, since i need the data in that format to be used in another application. However Michal solution, with the due adjustments, is working just fine. – Any Jan 27 '14 at 08:53

1 Answers1

3

You can do it using CsvListReader and CsvListWriter classes. Below you can see simple example how to do it:

CsvListReader reader = new CsvListReader(new FileReader(inputCsv), CsvPreference.STANDARD_PREFERENCE);
CsvListWriter writer = new CsvListWriter(new FileWriter(outputCsv), CsvPreference.STANDARD_PREFERENCE);
List<String> columns;
while ((columns = reader.read()) != null) {
    System.out.println("Input: " + columns);
    // Add new columns
    columns.add(1, "Column_2");
    columns.add("Last_column");

    System.out.println("Output: " + columns);
    writer.write(columns);
}
reader.close();
writer.close();

This is a simple example. You have to catch all exception and close streams in finally block.

Michał Ziober
  • 37,175
  • 18
  • 99
  • 146