Pergunta

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.

Foi útil?

Solução

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top