Java OpenCSV How to edit specific cells from csv file

I have a CSV file that looks like this: http://gyazo.com/5dcfb8eca4e133cbeac87f514099e320.png

I need to figure out how I can read certain cells and update them in a file.

This is the code I am using:

import java.util.List;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import com.opencsv.*;

public class ReadCSV {

    private static final char SEPARATOR = ';';

    public static void updateCSV(String input, String output, String  replace, int row, int col) throws IOException {   

          CSVReader reader = new CSVReader(new FileReader(input),SEPARATOR);
            List<String[]> csvBody = reader.readAll();
            csvBody.get(row)[col]=replace;
            reader.close();

            CSVWriter writer = new CSVWriter(new FileWriter(output),SEPARATOR,' ');
            writer.writeAll(csvBody);
            writer.flush();
            writer.close();
    }


    public static void main(String[] args) throws IOException {

        String source = "townhall_levels.csv";
        String destiantion="output.csv";
        ReadCSV.updateCSV(source, destiantion, "lol", 1, 1);

    }

}

      

In this code, I am just trying to change A1 to "lol" as an example test to see if it works, but I get the following error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
    at ReadCSV.updateCSV(ReadCSV.java:16)
    at ReadCSV.main(ReadCSV.java:30)

      

How can I achieve my goal and correct the error?

CSV file: www.forumalliance.net/townhall_levels.csv

+3


source to share


2 answers


You use ;

as delimiter to parse the file. Your file uses ,

. Also, using a space as a char quote doesn't make a lot of sense. You should use instead "

, as this is what your file is using.



0


source


The first values ​​you pass to string and col are 1 and 1. However, they must start at 0.



0


source







All Articles