如何将值写入CSV文件中的指定列
假设我想写入第四列,假设第一行的前三列已经有值。
我做不到
下面是我的代码
File outFile = new
File("C:\\docs\\test\\COLD_SOAK_1_engine_20171002014945.csv");
BufferedWriter out = new BufferedWriter(new FileWriter(outFile));
out.write(",,,4");
out.newLine();
out.close();
最佳答案
这是一个简单的 CSV 编辑类,具有基于 1 的索引。
public final class CSV {
private final List<String[]> cells;
public CSV(File file) throws IOException {
cells = new ArrayList<>();
try (Scanner scan = new Scanner(file)) {
while (scan.hasNextLine()) {
String line = scan.nextLine();
cells.add(line.split(","));
}
}
}
public String get(int row, int col) {
String columns = cells.get(row - 1);
return columns[col - 1];
}
public CSV set(int row, int col, String value) {
String columns = cells.get(row - 1);
columns[col - 1] = value;
return this;
}
public void save(File file) throws IOException {
try (PrintWriter out = new PrintWriter(file)) {
for (String[] row : cells) {
for (String cell : row) {
if (cell != row[0]) {
out.print(",");
}
out.print(cell);
}
out.printLn();
}
}
}
}
现在你可以做
File file = new
File("C:\\docs\\test\\COLD_SOAK_1_engine_20171002014945.csv");
new CSV(file).set(1, 4, "new value").save(file);
这不适用于值内包含引号的 CSV 文件。
关于java - 使用java写入CSV文件中的指定列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46533257/