[英]Reading from csv file give NumberFormatException?
我正在從csv文件中讀取數據並將所有數據設置為一個對象。特定點我得到一個數字格式異常(僅在讀取一些數據之后),因為一些數據不是數字(這是文件中的一些錯誤,一些字符數據在數字數據的位置,由於與主程序的某些集成問題而無法使用字符串概念)。在這一點上我需要跳過該行並需要移動到下一行。任何人都可以請求幫助。任何幫助都將非常值得注意。
reader = new CSVReader(new FileReader(parentPath+File.separator+file),',','"');
while ((nextLine = reader.readNext()) != null &&nextLine.length!=0 ) {
encap.setPrice((nextLine[5]));
String mrp=encap.getPrice().split("[,]")[0];
try {
encap.setProduct_price(Double.parseDouble(mrp));
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
注意:當特定行發生numberformat異常時,我需要跳過並閱讀下一行。(值正確,但每當發生數字格式異常時我的程序就會停止.......
封閉是我班級的對象....
擴大try catch的范圍。 蠻力,把嘗試放在下面,然后包括所有代碼,同時阻止在try塊中。
看起來你的try..catch
已經在正確的位置。 只需對每條記錄進行新的encap
,它應該按照您的意願運行:
List<Encap> encaps = new ArrayList<Encap>(); // <- create list of results
reader = new CSVReader(new FileReader(parentPath+File.separator+file),',','"');
while ((nextLine = reader.readNext()) != null &&nextLine.length!=0 ) {
Encap encap = new Encap(); // <- create a new instance for this line
encap.setPrice(nextLine[5]);
String mrp=encap.getPrice().split("[,]")[0];
try {
encap.setProduct_price(Double.parseDouble(mrp));
encaps.add(encap); // <- add this result to the list only if parsed ok
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.