Diego
Diego

Reputation: 23

How to delimit new line when reading CSV file?

I am trying to read a file where each line has data members, separated by commas, that are meant to populate an object's data members, I tried using the regex "|" symbol to separate "," and "\n" along with "\r" for getting to the new line. However, after reading the first line, the first data member of the second line does not get read right away but rather a "" character gets read beforehand. Am I using the wrong regex symbols? or am I not using the right approach? I read that there are many ways to tackle this and opted to use scanner since seemed the most simple, using the buffer reader seemed very confusing since it seems like it returns arrays and not individual strings and ints which is I'm trying to get.

The CSV file looks something like this

stringA,stringB,stringC,1,2,3
stringD,stringE,stringF,4,5,6
stringG,stringH,stringI,7,8,9

My code looks something like this

//In list class

public void load() throws FileNotFoundException
    {
        Scanner input = new Scanner(new FileReader("a_file.csv"));

        object to_add; //To be added to the list

        input.useDelimiter(",|\\n|\\r");

        while (input.hasNext())
        {
            String n = input.next(); //After the first loop run, this data gets the value ""
            String l = input.next(); //During this second run, this member gets the data that n was supposed to get, "stringD"
            String d = input.next(); //This one gets "stringE"
            int a = input.nextInt(); //And this one tries to get "stringF", which makes it crash
            int c = input.nextInt();

            to_add = new object(n, l, d, a, b, c); //Calling copy constructor to populate data members

            insert(to_add); //Inserting object to the list
        }

        input.close();
    }

Upvotes: 0

Views: 1149

Answers (2)

Hasitha Jayawardana
Hasitha Jayawardana

Reputation: 2436

You can do this with OpenCSV and here is a tutorial how to use this library. You can download the library from the Maven Repository.

So following is the code what you need to do,

Reader reader = Files.newBufferedReader(Paths.get("path/to/csvfile.csv"));
CSVReader csvReader = new CSVReader(reader);
List<String[]> dataList = new ArrayList<>();
dataList = csvReader.readAll();

reader.close();
csvReader.close();

Object to_add;

for (String[] rowData : dataList) {
    String textOne = rowData[0];
    String textTwo = rowData[1];
    String textThree = rowData[2];
    int numberOne = Integer.parseInt(rowData[3]);
    int numberTwo = Integer.parseInt(rowData[4]);
    int numberThree = Integer.parseInt(rowData[5]);

    to_add = new Object(textOne, textTwo, textThree, numberOne, numberTwo, numberThree);

    insert(to_add);
}

Upvotes: 0

Onur Başt&#252;rk
Onur Başt&#252;rk

Reputation: 735

Use Apache Commons CSV. Here is the user guide https://commons.apache.org/proper/commons-csv/user-guide.html

Upvotes: 1

Related Questions