java - 使用java写入CSV文件中的指定列

标签 java csv

如何将值写入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/

相关文章:

php - 如何使用 PHP 读取 csv 文件中的第二列?

java - hibernate 异常:could not insert collection rows

java - 由于架构验证,Spring Boot 项目无法运行 : missing sequence [hibernate_sequence]

c# - 减少主键数量

Java : CSV reading with ArrayList of List of Integer

javascript - 在 vue/typescript 中解析 CSV 文件

java - for 循环不迭代我的 HashMap 键集

java - 尝试将 int 变量从 Activity 传递到 Adapter

java - 如何在不使用 xpath 或 CSS 路径的情况下从 Amazon 页面定位元素?

python - 从 CSV 中删除尾随空格