0

This is a simple program to read from a text file, but somehow I am getting the following error when i run it

Exception in thread "main" java.lang.NullPointerException

Program:

package testenglish;

import java.util.*;
import java.io.*;


public class TestEnglish 
{

    public static void main(String[] args) 
    {
         Scanner myscanner= null;
        try
        {
                myscanner = new Scanner(new File("file.txt"));
        }
        catch (FileNotFoundException e)
        {

        }

        while (myscanner.hasNextLine())
        {

        }

        myscanner.close();
    }

}

enter image description here

I don't understand why I am getting a NullPointerException when myscanner has already been initialized.

EDIT: How come I am not reading the text file? It is placed in the same folder as the source code.

Eran
  • 387,369
  • 54
  • 702
  • 768
Computernerd
  • 7,378
  • 18
  • 66
  • 95

5 Answers5

3

This structure

Scanner myscanner= null;
try
{
    myscanner = new Scanner(new File("file.txt"));
}
catch (FileNotFoundException e)
{
}

is a very bad idea: essentially what you say is that you would like to load the file, but if anything goes wrong, it should fail silently. You catch the exception, but then don't do anything with it (except implicitly squash it by catching it).

If the code fails, myscanner will still be uninitialised. You'll then get a null pointer exception when you try to use it. That's what's happening to you.

You want to try either

try
{
    myscanner = new Scanner(new File("file.txt"));
    //now do your processing inside here
}
catch (FileNotFoundException e)
{
    e.printStackTrace();
}

or else get rid of the try/catch structure and add throws FileNotFoundException to your method signature:

public static void main(String[] args) throws FileNotFoundException

As for why you're not finding the file, it's not a question of whether it's in the same directory as the source, it's whether it's in the directory from which the program is being invoked, which is not quite the same thing. The safest option would be to put the entire path in there. If you're on Windows, remember you need to use \\ wherever you'd have a single \, because a single \ has a different meaning in Java.

chiastic-security
  • 20,430
  • 4
  • 39
  • 67
2

If you get FileNotFoundException, you do nothing (your catch block is empty), and then proceed to accessing myscanner, which is not initialized (and is therefore null).

You should move your while loop inside the try block, so that you only read from myscanner if it was successfully initialized. You should also check that myscanner != null before trying to close it.

Eran
  • 387,369
  • 54
  • 702
  • 768
1

Nullpointer Exception is happening as the file is not getting read and myScanner is null. The exception comes when hasnextLine() is called on a null value. The problem seems to be with file path.

Kick Buttowski
  • 6,709
  • 13
  • 37
  • 58
Dhan
  • 42
  • 2
1

You get a NullPointerException because the File constructor does not find the file in the classpath. Instead, what you can do is to create your scanner object from an InputStream, like this:

    Scanner myscanner = null;
    try {
        InputStream is = TestEnglish.class.getResourceAsStream("file.txt");

        myscanner = new Scanner(is);
        if (myscanner != null) {
            while (myscanner.hasNextLine()) {

            }
        }
    } catch (Exception e) {
        e.printStackTrace();

    } finally {
        if (myscanner != null)
            myscanner.close();
    }    

Note: In this case try to also use finally to close your Scanner appropriately.

0
// From Class, the path is relative to the package of the class unless
// you include a leading slash, so if you don't want to use the current
// package, include a slash like this:

InputStream in = this.getClass().getResourceAsStream("file.txt");
DeepInJava
  • 1,871
  • 3
  • 16
  • 31