简体   繁体   English

线程“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);

Also, should I add throws IOException, FileNotFoundException to main or use try{} instead? 另外,我应该添加抛出IOException,FileNotFoundException到main还是使用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);

You've made the classic mistake of catching the exception (in this case FileNotFoundException) and not actually recovering from it. 你犯了一个经典的错误:捕获异常(在这种情况下是FileNotFoundException)而不是实际从中恢复。 So when the file open fails, you are then passing a null argument to InputStreamReader(...) , and that is causing the NPE. 因此,当文件打开失败时,您将传递null参数到InputStreamReader(...) ,这就是导致NPE。

Also, should I add throws IOException, FileNotFoundException to main or use try{} instead? 另外,我应该添加抛出IOException,FileNotFoundException到main还是使用try {}?

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. 您必须决定是否要将异常传播到main (可能必须放弃),或者是否希望当前方法尝试恢复。 For instance, you could ask for a different filename ... 例如,你可以要求一个不同的文件名......

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. 顺便提一下,由于您已经使用Scanner从stdin读取,因此您还应该使用Scanner来读取文件。 I think BufferedReaders are bit clunky to work with. 我认为BufferedReaders有点笨拙可以使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM