简体   繁体   中英

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?

    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. 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 ...

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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