Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/326.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用java写入CSV文件中的指定列_Java_Csv - Fatal编程技术网

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

使用java写入CSV文件中的指定列,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("

如何将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();
            }
        }
    }
}

但这不适用于在值中引用逗号的CSV文件。

您需要读取文件内容,修改文件以插入新值,然后再次将其写入文件。您正在做的是覆盖当前内容谢谢Peter您有示例代码吗?不是针对您的特定用途没有,但是一个简单的google for java读写文件示例应该可以让您很快达到目的
File file = new 
    File("C:\\docs\\test\\COLD_SOAK_1_engine_20171002014945.csv");
new CSV(file).set(1, 4, "new value").save(file);