wpd
wpd

Reputation: 21

write to specified column in CSV file using java

How to write values in CSV file in the specified column

for suppose i want to write to 4th column assuming that first three columns of first row already has the values.

I am not able to do that

below is my code

        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();

Upvotes: 0

Views: 3216

Answers (1)

Leo Aso
Leo Aso

Reputation: 12463

Here is a simple CSV editing class with 1-based indexing.

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

Now you can do

File file = new 
    File("C:\\docs\\test\\COLD_SOAK_1_engine_20171002014945.csv");
new CSV(file).set(1, 4, "new value").save(file);

This does not work for CSV files that have quoted commas within values though.

Upvotes: 1

Related Questions