Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Reading CSV file into array but ignore first line

Tags:

java

sql

csv

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. When the code read the first line i will get errors.

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);
        }
like image 303
BeyondProgrammer Avatar asked Jun 04 '26 13:06

BeyondProgrammer


2 Answers

Add a readLine() before the while loop to skip the first line.

br = new BufferedReader(new FileReader(file));
br.readLine(); //read the first line and throw it away
while ((line = br.readLine()) != null) {
like image 104
user2336315 Avatar answered Jun 07 '26 02:06

user2336315


br = new BufferedReader(new FileReader(file));
br.readLine() // Read first line and skip...
            while ((line = br.readLine()) != null) { .......
...
like image 30
TheLostMind Avatar answered Jun 07 '26 04:06

TheLostMind



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!