man*_*ear 2 java apache-commons-csv
我有一个使用 Apache commons API 编写的 csv 文件,我也可以读取该文件,但是我无法知道如何使用 Apache commons API 编辑 csv 文件中的记录值,需要这方面的帮助。
我尝试了下面的代码,它的工作原理完全符合我的预期。
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();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7038 次 |
| 最近记录: |