3

I have a csv file that look like this:

name,age,total
xyz,22
abc,20

After processing the csv file should look like this:

name,age,total
xyz,22,100
abc,20,102

After running this code:

public class Converter {

    public static void main(String[] args) throws IOException {
        
        BufferedWriter writer = Files.newBufferedWriter(Paths.get(Constants.SAMPLE_CSV_FILE));
        CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT);
        
        csvPrinter.print(100);
        csvPrinter.print(102);
        
        csvPrinter.close();
    }

}

the output csv file becomes like this:

100
102

I want 100 and 102 to come under the total column. How can I do this?

1
  • 1
    You never actually read the existing data in. You have to read the data and add the field to every line and then write the updated line. Commented Dec 31, 2017 at 7:39

1 Answer 1

0

First of all, you shouldn't override your existing file. Hence, use the appending argument on the FileWriter constructor:

FileWriter pw = new FileWriter("C:\\exampleFile.csv",true); 

Second, as you can see in your result, the CSVPrinter goes through your file by rows. If you want to add a new column, you actually need to iterate over each row and insert the new column's row data on every iteration, as explained thoroughly here

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.