Reputation: 1601
I have a csv file written using Apache commons API and I also can read the file, however I'm unable to know how to edit a record value in the csv file using Apache commons API, need help on this.
Upvotes: 2
Views: 7690
Reputation: 1601
I tried the below code and it worked exactly the way I expected.
public static void updateCsvFile(File f) throws Exception {
CSVParser parser = new CSVParser(new FileReader(f), CSVFormat.DEFAULT);
List<CSVRecord> list = parser.getRecords();
String edited = f.getAbsolutePath();
f.delete();
CSVPrinter printer = new CSVPrinter(new FileWriter(edited), CSVFormat.DEFAULT.withRecordSeparator(NEW_LINE_SEPARATOR));
for (CSVRecord record : list) {
String[] s = toArray(record);
if(s[0].equalsIgnoreCase("Actual Text")){
s[0] = "Replacement Text";
}
print(printer, s);
}
parser.close();
printer.close();
System.out.println("CSV file was updated successfully !!!");
}
public static String[] toArray(CSVRecord rec) {
String[] arr = new String[rec.size()];
int i = 0;
for (String str : rec) {
arr[i++] = str;
}
return arr;
}
public static void print(CSVPrinter printer, String[] s) throws Exception {
for (String val : s) {
printer.print(val != null ? String.valueOf(val) : "");
}
printer.println();
}
Upvotes: 5
Reputation: 15882
The Apache CSV interface only support reading and writing exclusively, you cannot update records with the provided API.
So your best option is probably to read the file into memory, do the changes and write it out again.
If the size of the file is bigger than available memory you might need some streaming approach which reads records and writes them out before reading the next one. You need to write to a separate file in this case naturally.
Upvotes: 1