Search code examples
javacsvopencsv

opencsv read from an unknow line but known word?


Ok, i have a csv file:

Summary
    heading1,heading2,heading3
    value1,value2,value2
    value1,value2,value2
    value1,value2,value2
    value1,value2,value2
Detail
    heading11,heading12,heading13
    value1,value2,value2
    value1,value2,value2
    value1,value2,value2
    value1,value2,value2

I'm using the com.opencsv.CSVReader library.

I need to read from the line "Detail", however I don't know which row it is, because there can be an undefined amount of rows before it. Summary starts from
row 13, but I know how to work with that.

Is there an easy mode for opencsv to find the row "Detail" and start from there? Or do i need to somehow count the rows before Detail and pass it into OPENCSV as a parameter?


Solution

  • Since dividing a CSV into sections is not a common requirement and not necessarily supported by the library, you should find yourself the point where the rows you are interested in start and extract them. One way could be:

    BufferedReader b = new BufferedReader(new FileReader(source));
    String line = b.readLine();
    StringBuilder build = new StringBuilder();
    while(line != null && !line.equals("Detail")){
        line = b.readLine();
    }
    line = b.readLine();
    while(line != null){
        build.append(line);
        build.append('\n');
        line = b.readLine();
    }
    System.out.println(build.toString());
    Reader toBeParsed = new StringReader(build.toString());
    

    Which basically reads the file until a line matching the Detail part is found then adds all the remaining rows into a String. From this string a reader is used that can be fed into CSVReader.

    I assume that all the remaining rows must be considered ( consider to match against another string to stop that if that's not the case), and that the line where to start is exactly "Detail" (you can use a regex for a more flexible approach)

    Here is a live demo