java - NullPointerException during File IO -
this simple programme read text file, somehow getting next error when run
exception in thread "main" java.lang.nullpointerexception
program:
package testenglish; import java.util.*; import java.io.*; public class testenglish { public static void main(string[] args) { scanner myscanner= null; seek { myscanner = new scanner(new file("file.txt")); } grab (filenotfoundexception e) { } while (myscanner.hasnextline()) { } myscanner.close(); } }
i don't understand why getting nullpointerexception
when myscanner
has been initialized.
edit: how come not reading text file? placed in same folder source code.
this structure
scanner myscanner= null; seek { myscanner = new scanner(new file("file.txt")); } grab (filenotfoundexception e) { }
is bad idea: load file, if goes wrong, should fail silently. grab exception, don't (except implicitly crush catching it).
if code fails, myscanner
still uninitialised. you'll null pointer exception when seek utilize it. that's what's happening you.
you want seek either
try { myscanner = new scanner(new file("file.txt")); //now processing within here } grab (filenotfoundexception e) { e.printstacktrace(); }
or else rid of try
/catch
construction , add together throws filenotfoundexception
method signature:
public static void main(string[] args) throws filenotfoundexception
as why you're not finding file, it's not question of whether it's in same directory source, it's whether it's in directory programme beingness invoked, not quite same thing. safest alternative set entire path in there. if you're on windows, remember need utilize \\
wherever you'd have single \
, because single \
has different meaning in java.
java file-io
No comments:
Post a Comment