NafisDroid
NafisDroid

Reputation: 27

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 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)

Upvotes: 0

Views: 367

Answers (2)

M Sach
M Sach

Reputation: 34424

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); 
} 

Upvotes: 1

Shriram
Shriram

Reputation: 4411

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

Upvotes: 1

Related Questions