0

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();
3
  • 1
    You need to read the contents of the file, modify it to insert your new value then write it to the file again. What you are doing is overwriting the current content Commented Oct 2, 2017 at 20:31
  • Thanks Peter do you have sample code? Commented Oct 2, 2017 at 20:32
  • Not for you specific use no, but a simple google for java read and write file example should get you there quickly Commented Oct 2, 2017 at 20:35

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.