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);
另外,我应该在 main 中添加 throws IOException、FileNotFoundException 还是使用 try{} ?
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);
最佳答案
您犯了一个典型的错误:捕获异常(在本例中为 FileNotFoundException),但实际上并未从中恢复。因此,当文件打开失败时,您会将 null
参数传递给 InputStreamReader(...)
,这会导致 NPE。
Also, should I add throws IOException, FileNotFoundException to main or use try{} instead?
这取决于您的要求。您必须决定是否要让异常传播到 main(这可能必须放弃),或者是否希望当前方法尝试恢复。例如,您可以要求不同的文件名...
关于java - 线程中出现异常 "main"java.lang.NullPointerException InputStreamReader,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9510174/