0

I can't read an integer from a text file using a 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)
1
  • From javadoc "A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached". try adding a check while((str=br.readLine())!=null && str.length()!=0) Commented May 29, 2015 at 17:54

2 Answers 2

1

Make sure that the value read from file is not null and integer. Otherwise you will get the Exception. Because readLine returns the whole line from the file as string

Sign up to request clarification or add additional context in comments.

1 Comment

Yap file was not saved ...I just forget to save the file.. Thanx
1

Looks file is empty. To make sure your covers this case as well handle for null

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.