简体   繁体   English

为什么不能使用BufferedReader从文本文件读取整数?

[英]Why can't I read an integer from a text file using a BufferedReader?

I can't read an integer from a text file using a BufferedReader: 我无法使用BufferedReader从文本文件读取整数:

BufferedReader br = new BufferedReader(new FileReader("C:/heapsort.txt"));
s = br.readLine();
int x = Integer.parseInt(s);

The code above throws the following exception: 上面的代码引发以下异常:

ava.lang.NumberFormatException: null
    at java.lang.Integer.parseInt(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at tester.main(tester.java:16)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)

Make sure that the value read from file is not null and integer. 确保从文件读取的值不是null和integer。 Otherwise you will get the Exception. 否则,您将获得异常。 Because readLine returns the whole line from the file as string 因为readLine将文件中的整行作为字符串返回

Looks file is empty. 看起来文件为空。 To make sure your covers this case as well handle for null 为了确保您能解决此问题,请处理null

while((br = br.readLine()) != null) { 
int x = Integer.parseInt(s);
System.out.println(br); 
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM