Reputation: 6351
I haven't written any Java in years and I went back to refresh my memory with a simple 'read-from-file' example. Here is my code..
import java.io.*;
public class filereading {
public static void main(String[] args) {
File file = new File("C:\\file.txt");
FileInputStream fs = null;
BufferedInputStream bs = null;
DataInputStream ds = null;
try
{
fs = new FileInputStream(file);
bs = new BufferedInputStream(bs);
ds = new DataInputStream(ds);
while(ds.available()!= 0)
{
String readLine = ds.readLine();
System.out.println(readLine);
}
ds.close();
bs.close();
fs.close();
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
This compiles fine (although apparently ds.readLine() is deprected), but at runtime, this gives me
Exception in thread "main" java.lang.NullPointerException at java.io.FilterInputStream.available(Unknown Source) at filereading.main(filereading.java:21)
What gives?
Upvotes: 0
Views: 3371
Reputation: 192015
You made a simple typo:
ds = new DataInputStream(ds);
should be
ds = new DataInputStream(bs);
Your code is initializing the DataInputStream
with a null source, since ds
hasn't been created yet.
Having said that, Jon Skeet's answer gives a better way to write a file-reading program (and you should always use Readers
/Writers
rather than Streams
when dealing with text).
Upvotes: 6
Reputation: 1502686
To read a text file, use BufferedReader
- in this case, wrapped round an InputStreamReader
, wrapped round a FileInputStream
. (This allows you to set the encoding explicitly - which you should definitely do.) You should also close resources in finally blocks, of course.
You should then read lines until readLine()
returns null, rather than relying on available()
IMO. I suspect you'll find that readLine()
was returning null
for the last line in the file, even though available()
returned 2 to indicate the final \r\n
. Just a hunch though.
String line;
while ((line = reader.readLine()) != null)
{
System.out.println(line);
}
Upvotes: 3