Ngoni Choga Ngoni Choga - 1 month ago 4
Java Question

Add/append data to specific row/cell of an existing CSV file

I'm trying to append a value to a specific row in a csv file but append'd default is to add the value at the end of the csv file. Not exactly sure how to tell it to append at the end of a specific row. My code looks like the following:

try {
writer = new FileWriter(csvFile ,true);
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {

// use comma as separator
String[] id = line.split(cvsSplitBy);

if(id[0].equals("1")){
writer.append(",");
writer.append("Success");
System.out.println("Done");
}
}

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}


The goal is to make the program add "success" where the csv row id is equal to 1. Current result is:

Id,Name,Sex,Age
1,Nick,Male,23
2,Dick,Male,25,Success


What I would like is:

Id,Name,Sex,Age
1,Nick,Male,23,Success
2,Dick,Male,25


Any help would be appreciated. Thanks.

Answer

You can't just append to the end of a line and expect the following lines to stay where they are. Think about the structure of a text file, e.g. one containing the following lines:

one
two

This file is contains the following sequence of characters:

"o", "n", "e", "\n", "t", "w", "o", "\n"

Now, if you add more characters at the end of line 1, you will overwrite line 2.

Therefore, when you insert characters at the end of a line, you need to shift the remainder of the file to make space. That means you have to copy the contents of the remainder of the file, write your ", Success" string, then copy the saved characters back to the file.

But you're creating a FileWriter with the append flag set to true. That means every write appends to the end of the file. What you need to do, instead of appending, is mark the position where you need to write, and start writing at that position. Perhaps the easiest class for doing this is RandomAccessFile.

Comments