CSV在java中读取 [英] CSV reading in java
本文介绍了CSV在java中读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在从CSV档案读取时遇到问题
Im having trouble reading from a CSV file
final String DELIMITER = ",";
Scanner fileScan = null;
Scanner dataSetScan = null;
String dataSet = null;
String sql = "";
File users = new File("user.txt");
String nickname = "";
String lastname = "";
String firstname = "";
String cartype = "";
String personimage = "";
String carimage = "";
int user_id = 0;
try {
fileScan = new Scanner(users);
} catch (Exception e) {
System.out.println(e);
}
while(fileScan.hasNext()){
dataSet = fileScan.nextLine();
dataSetScan = new Scanner(dataSet);
dataSetScan.useDelimiter(DELIMITER);
nickname = dataSetScan.next();
lastname = dataSetScan.next();
firstname = dataSetScan.next();
cartype = dataSetScan.next();
personimage = dataSetScan.next();
carimage = dataSetScan.next();
sql += "INSERT INTO users VALUES (";
sql += user_id++ + ", ";
sql += "'" + nickname + "', ";
sql += "'" + lastname + "', ";
sql += "'" + firstname + "', ";
sql += "'" + cartype + "', ";
sql += "'" + personimage + "', ";
sql += "'" + carimage + "' ";
sql += ");\n";
}
上述代码不适用于示例文件
The above code wont work on the example file
alice,Wonder-Land,Alice,red Vauxhall Corsa,alice.jpg,alice_car.jpg
bob,Kett,Robert,,,
charlie,Carlos,Don,,,
在行尾有一个逗号。 (hvaing这里的逗号不是一个选项)
However, it works just fine when there is a comma at the end of the line. (hvaing a comma here is not an option)
我能做什么使这项工作?
What can i do to make this work? It must be to do with my delimeter i think
谢谢
推荐答案
p>您是否从以下行获得NoSuchElementException?
Are you getting a NoSuchElementException from the following line?
carimage = dataSetScan.next();
如果是这样,你只需要使用hasNext检查,
If so you just need to wrap that with a hasNext check and perform a null check when you build your string.
if(dataSetScanner.hasNext()){
carimage = dataSetScan.next();
}
else{
carimage = null;
}
...
sql += carimage == null ? "NULL" : "'" + carimage + "' ";
这篇关于CSV在java中读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文