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.

3
  • Hi, this was answered on the Super CSV discussion board. 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. Commented Jan 22, 2014 at 21:46
  • Also related to stackoverflow.com/q/11035602/1068649 Commented Jan 22, 2014 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. Commented Jan 27, 2014 at 8:53

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.