【发布时间】:2013-01-19 15:11:10
【问题描述】:
我有一个 BufferedReader 遍历 CSV 文件的行;当它到达文件末尾时,它返回以下错误:
Exception in thread "main" java.lang.NumberFormatException: empty String
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:992)
如何让读者意识到它已到达文件末尾并且输入为空而不是空?我检查了文件,最后一行末尾没有空格。
代码:
File filReadMe = new File(inputFile);
BufferedReader brReadMe = new BufferedReader(new InputStreamReader(new FileInputStream(filReadMe), "UTF-8"));
try
{
String strLine;
while ((strLine = brReadMe.readLine()) != null)
{
System.out.println(strLine);
//place the line into CsvRecordFactory
int record = csv.processLine(strLine, input);
}
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
//Close the BufferedReader
try {
if (brReadMe != null)
brReadMe.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
【问题讨论】:
-
文件的最后一行包含一个空的
String,因此您应该检查strLine.equals("")是否作为停止while-loop的另一个条件。 -
strLine.isEmpty() 在语义上会比 strLine.equals("")
-
感谢 Luiggi 和 Cyrille。你知道我的语法有什么问题吗?我仍然看到同样的错误。 while ((strLine = brReadMe.readLine()) != null && !strLine.isEmpty())
-
@Luiggi Mendoza - 如果 strLine 为
null,则通常最好使用"".equals(strLine)来避免潜在的 NPE。 -
尝试将
System.out.println(strLine);更改为System.out.println("\"" + strLine + "\"");以帮助确认从文件中检索到的每一行的值。
标签: java null bufferedreader string