问题
Exception in thread "main" java.lang.NullPointerException
at java.io.Reader.<init>(Unknown Source)
at java.io.InputStreamReader.<init>(Unknown Source)
//at InputStreamReader inStream = new InputStreamReader(fis);
Also, should I add throws IOException, FileNotFoundException to main or use try{} instead?
System.out.print("Enter the filename: ");
Scanner stdin = new Scanner(System.in); //Keyboard input
String fileName=stdin.nextLine();
FileInputStream fis = null;
try {
fis = new FileInputStream(fileName);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
InputStreamReader inStream = new InputStreamReader(fis);
BufferedReader in = new BufferedReader(inStream);
回答1:
You've made the classic mistake of catching the exception (in this case FileNotFoundException) and not actually recovering from it. So when the file open fails, you are then passing a null
argument to InputStreamReader(...)
, and that is causing the NPE.
Also, should I add throws IOException, FileNotFoundException to main or use try{} instead?
That depends on your requirements. You have to decide whether you want to let the exceptions to propagate to main
(which will probably have to give up), or whether you want the current method to attempt to recover. For instance, you could ask for a different filename ...
回答2:
The code works. Just tested it myself. The file name you're entering must not be there.
Incidentally, since you're already using a Scanner
to read from stdin, you should also use a Scanner
to reader your file. I think BufferedReaders
are bit clunky to work with.
来源:https://stackoverflow.com/questions/9510174/exception-in-thread-main-java-lang-nullpointerexception-inputstreamreader