Exception in thread “main” java.lang.NullPointerException InputStreamReader

青春壹個敷衍的年華 提交于 2021-01-29 06:36:00

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!