Search code examples
javaopencsv

read a csv file from the beginning after having reached the end (Java, OpenCSV)


I want to use OpenCSV and Java to count how many lines a specific .csv file of mine has. Then, I want to parse every line of the file and do some stuff. I found some questions similar to mine and the most common answer to these questions was to use a loop to count the lines, as CSVReader class doesn't have a function that counts the lines of the file it's reading. My question is the following: After I count the lines, is there a way to read the file from the beginning after the first loop, without creating a new CSVReader object and String buffer? Thanks in advance.

EDIT: I ended up using the readAll() member function of CSVReader class. It stores the whole file to a List of String arrays. Every row is a List node, with every entry of the row being a String in the String array. This way, you can also very easily get the number of rows like this:

List<String[]> records = csvReader.readAll();
int no_of_rows = records.size();

import com.opencsv.CSVReader;
import java.io.Reader;
import java.nio.file.Files;
import java.nio.file.Paths;

public class CSV_Reader {
private static final String SAMPLE_CSV_FILE_PATH = "some_path";

public static void main(String[] args) {
    try {
        Reader reader = Files.newBufferedReader(Paths.get(SAMPLE_CSV_FILE_PATH));
        System.out.println("before new object");
        CSVReader csvReader = new CSVReader(reader);
        String[] nextRecord;
        System.out.println("before while");

        int no_of_rows = 0;
        while ( (nextRecord = csvReader.readNext()) != null ) {
            no_of_rows++;
        }

        System.out.println("Number of lines is: " + no_of_rows );

        String[] string_vector = new String[no_of_rows];
        while ((nextRecord = csvReader.readNext()) != null) {
            //I want to do some stuff here. It doesn't enter the loop as it is now...
        }

Solution

  • Not sure what you are trying to do but if it is really something that you want to do by storing each line's data then here is what you can do.

    CSVReader csvReader = new CSVReader(reader);
    List<List<String>> rows = new ArrayList<>();
    String[] nextRecord;
    while ((nextRecord = csvReader.readNext()) != null) {
      rows.add(Arrays.asList(nextRecord)); //rows is a list of list
      //do whatever you want to do
    }