Java - Reading input from a file. java.io.FilterInputStream.available(Unknown Source)? -
i haven't written java in years , went refresh memory simple 'read-from-file' example. here 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() deprected), @ runtime, gives me
exception in thread "main" java.lang.nullpointerexception @ java.io.filterinputstream.available(unknown source) @ filereading.main(filereading.java:21)
what gives?
you made simple typo:
ds = new datainputstream(ds);
should be
ds = new datainputstream(bs);
your code initializing datainputstream
null source, since ds
hasn't been created yet.
having said that, jon skeet's answer gives better way write file-reading program (and should use readers
/writers
rather streams
when dealing text).
Comments
Post a Comment