tags:

views:

279

answers:

2

Hi. 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?

+2  A: 

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);
}
Jon Skeet
+6  A: 

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

Michael Myers
And the previous line.
Tom Hawtin - tackline
Solution: Use much better variable names!
Tom Hawtin - tackline
The line above that is incorrect too - it should be BufferedInputStream(fs) rather than BufferedInputStream(bs)
danmec
Heh, I didn't even notice that one. Better variable names would definitely help here.
Michael Myers
I've gotta stop writing code so early in the morning. Thanks!
Mark