![](/img/trans.png)
[英]java - Exception in thread “main” java.lang.NumberFormatException: For input string: “” at
[英]Exception in thread “main” java.lang.NumberFormatException: For input string: “” in Java
我在Java中创建了一个类,以读取文本文件(.txt),并在屏幕上打印结果。 脚本正在读取文本文件的内容,但最后显示消息:
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:592)
at java.lang.Integer.parseInt(Integer.java:615)
at com.desafioProgramacao.LerArquivo.main(LerArquivo.java:24)
我不知道为什么它显示消息。 在FINALLY类中,我告诉它如果文件的内容为null,则关闭FileReader和BufferedReader。 遵循Java代码和屏幕打印。
public class LerArquivo {
private static final String NomeArquivo = "E:\\DesafioProgramacao\\matriculasSemDV.txt";
public static void main(String[] args) {
FileReader fr = null;
BufferedReader br = null;
try {
fr = new FileReader(NomeArquivo);
br = new BufferedReader(fr);
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
int num = Integer.parseInt(sCurrentLine);
System.out.println(num);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null) {
br.close();
}
if (fr != null) {
fr.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}}
表面上的原因是您读取了一个空字符串并将其解析为int
对于代码,您需要检查sCurrentLine
值
while ((sCurrentLine = br.readLine()) != null) {
if(StringUtils.isNotBlank(sCurrentLine)){//StringUtils is from `commons-lang`
// or if(sCurrentLine.length()>0)
int num = Integer.parseInt(sCurrentLine);
System.out.println(num);
}
}
对于txt文件,您需要删除文件末尾的所有空行
您的文件包含一个空行(可能在末尾)。
将您的while循环替换为:
while ((sCurrentLine = br.readLine()) != null && !sCurrentLine.isEmpty())
问题是最后一行,它是空白。 你可以做:
while ((sCurrentLine = br.readLine()) != null) {
if (!sCurrentLine.isEmpty()) {
int num = Integer.parseInt(sCurrentLine);
System.out.println(num);
}
}
修复它的正确方法是捕获该NumberFormatException并正确处理它,如下所示:
try {
int num = Integer.parseInt(sCurrentLine);
System.out.println(num);
} catch (NumberFormatException ex) {
System.out.println("Error reading line: " + sCurrentLine);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.