How to print these csv file in a specific format copy

 

问题

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

I'm trying to read CSV file using header. I am Using this 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 wanted to read 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 csv using header while skipping the other lines. Thank you in advance.

解答

这个问题需要跳过CSV 文件中的前 n 行后再解析。Apache Commons CSV 库没有现成的方法跳过前 n 行,需要自己写 JAVA 代码实现。

Java 下的开源包 SPL 很容易写,只要 1 句:


A

1

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

SPL提供了JDBC 供 JAVA 调用,把上面的脚本存为 skiplines.splx,在 JAVA 中以存储过程的方式调用脚本文件:

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

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

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

st.execute();

或在JAVA 中以 SQL 方式直接执行 SPL 串:

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

st.execute();

SPL 源代码:https://github.com/SPLWare/esProc

问答搜集