线程"main"中的异常java.lang.NullPointerException InputStreamReader [英] Exception in thread "main" java.lang.NullPointerException InputStreamReader
问题描述
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);
此外,我应该向主添加抛出IOException,FileNotFoundException还是使用try {}?
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);
推荐答案
您已经犯了一个经典错误,即捕获异常(在本例中为FileNotFoundException),而实际上并未从中恢复.因此,当文件打开失败时,您需要将 null
参数传递给 InputStreamReader(...)
,这将导致NPE.
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.
此外,我应该向主机添加抛出IOException,FileNotFoundException异常还是使用try {}?
Also, should I add throws IOException, FileNotFoundException to main or use try{} instead?
这取决于您的要求.您必须决定是否要让异常传播到 main
(可能必须放弃),还是要让当前方法尝试恢复.例如,您可以要求使用其他文件名...
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 ...
这篇关于线程"main"中的异常java.lang.NullPointerException InputStreamReader的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!