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();
}
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)
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
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.