How to Print These CSV File in a Specific Format Copy

Question

Source: https://stackoverflow.com/questions/69673907/read-csv-using-header-while-ignoring-some-lines-in-java

I'm trying to read a CSV file having the header. I am using the following code:

public String getSpecificCSVDataUsingHeader(String filePath, String header) {

        String value = "";

        String basePath = new File(filePath).getAbsolutePath();

        try (

                BufferedReader br = new BufferedReader(new FileReader(basePath));

                org.apache.commons.csv.CSVParser parser = CSVFormat.DEFAULT.withDelimiter(',').withHeader().parse(br);

         ) {

            for (CSVRecord record : parser) {

                value = record.get(header);

            }

            return value;

        } catch (IOException e) {

            LogUtil.error(this, e.getMessage());

        }

        return value;

    }

It works perfectly for this kind of CSV (where the first line is header): 

color1,color2,color3

black,blue,red

 

Now I want to read the CSV with some lines before the actual header, like this one: 

some lines…

some lines…

 

color1,color2,color3

black,blue,red

Is there any way where I could read a CSV retaining the header while skipping other lines? Thank you in advance.

Answer

Let me describe your problem. You need to skip the first n lines (except the header) in the CSV file and parse it. There isn’t a ready-to-use method in Apache Commons CSV library to skip the n lines. So you have to write your own Java code to do this.

It is simple to get it done using Java’s open-source package SPL. You just need one line of code:

A

1

=file("skip3lines.txt").read@n().to(4;).export().import@ct()

 

SPL offers JDBC driver to be invoked by Java. Just store the above SPL script as skiplines.splx and invoke it in Java as you call a stored procedure:

Class.forName("com.esproc.jdbc.InternalDriver");

con = DriverManager.getConnection("jdbc:esproc:local://");

st = con.prepareCall("call skiplines()");

st.execute();

Or execute the SPL string within a Java program as we execute a SQL statement:

st = con.prepareStatement("==file(\"skip3lines.txt\").read@n().to(4;).export().import@ct()");

st.execute();

View SPL source code.