简体   繁体   English

Java将CSV文件读入数组但忽略第一行

[英]Java Reading CSV file into array but ignore first line

I have written the following codes, however I will need to skip the first line as it is the field name. 我已经编写了以下代码,但是我将跳过第一行,因为它是字段名称。 My file here is cart.csv. 我的文件在这里是cart.csv。 When the code read the first line i will get errors. 当代码读取第一行时,我将得到错误。

cart.csv cart.csv

Number,Item,Quantity
1,Book,10
2,Fruit,14
3,Toy,2

code

 try {

            br = new BufferedReader(new FileReader(file));
            while ((line = br.readLine()) != null) {

                // use comma as separator
                String[] data = line.split(",");

                String sql = "INSERT INTO DB (Number,Item,Quantity) values (?, ?, ?)";
                pstmt = conn.prepareStatement(sql);
                pstmt.setString(1, data[0]);
                pstmt.setString(2, data[1]);
                pstmt.setString(3, data[2]);
                pstmt.executeUpdate();
                System.out.println("Upload Completed");
    }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SQLException ex) {
            Logger.getLogger(POI.class.getName()).log(Level.SEVERE, null, ex);
        }

Add a readLine() before the while loop to skip the first line. 在while循环之前添加readLine()以跳过第一行。

br = new BufferedReader(new FileReader(file));
br.readLine(); //read the first line and throw it away
while ((line = br.readLine()) != null) {
br = new BufferedReader(new FileReader(file));
br.readLine() // Read first line and skip...
            while ((line = br.readLine()) != null) { .......
...

For CSV read use SuperCSV. 对于CSV读取,请使用SuperCSV。 Awesome library. 很棒的图书馆。 You can just do something like below to skip header. 您可以像下面这样跳过标题。

listReader = new CsvListReader(new FileReader(CSV_FILENAME), CsvPreference.STANDARD_PREFERENCE);
listReader.getHeader(true); 

http://supercsv.sourceforge.net/examples_reading.html http://supercsv.sourceforge.net/examples_reading.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM