Question

My File is located in my /res, more specifically its in /res/Menus/CharSelect. I have already gone into my build path and made sure the res folder is a class path. However, my new Scanner(file) is causing a NullPointerException. When I do file.exists(); it returns FALSE... and I can't figure out why. I am 100% that the file does exist, and that it is located in the CharSelect folder. Can any one help? Thanks in advance.

    file = new File(getClass().getResource("/Menus/CharSelect/Unlocked.txt").getPath());
    try
    {
        scanner = new Scanner(file);
    }
    catch (FileNotFoundException e)
    {
        e.printStackTrace();
    }
Was it helpful?

Solution

Don't do that. When you'll create a jar you won't have access to that file as a File object but as an URL from which you'll have to get the InputStream with openStream().

Instead, use the Scanner(InputStream) with:

try (InputStream is = getClass().getResource("/Menus/CharSelect/Unlocked.txt").openStream()) {
    scanner = new Scanner(is);
    ...
} // is.close() called automatically by try-with-resource block (since Java 7)

OTHER TIPS

someClass.getResource resolve paths relatively to someClass location. Move your file to PATH_TO_THIS_CLASS_PATH/Menus/CharSelect/Unlocked.txt and operation must succeed

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top