我已经编写了以下代码,但是我需要跳过第一行,因为它是字段名称。我这里的文件是 cart.csv。当代码读取第一行时,我会收到错误。
购物车.csv
Number,Item,Quantity
1,Book,10
2,Fruit,14
3,Toy,2
代码
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);
}
最佳答案
在 while 循环之前添加一个 readLine()
以跳过第一行。
br = new BufferedReader(new FileReader(file));
br.readLine(); //read the first line and throw it away
while ((line = br.readLine()) != null) {
关于Java将CSV文件读入数组但忽略第一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20798936/