What is causing this ClassLoader- and File-related NullPointerException? [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I'm creating a method that is supposed to find the path to a text file and return it as a String to be used for a configuration file. Here's the block of code that is being affected:
public String getConfigLocation() {
String fileName = "locateconfig.txt";
ClassLoader classLoader = ClassLoader.getSystemClassLoader();
File file = new File(classLoader.getResource(fileName).getFile());
locationFile = file.getAbsolutePath();
return locationFile;
}
The line that's causing this exception to be thrown is File file = new File(classLoader.getResource(fileName).getFile());.
Here's the first few lines of the stack trace - just the first few, because all the methods being affected here interact with the one I'm having a problem with.
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at epicorexpert.EpicoreJFrame.getConfigLocation(EpicoreJFrame.java:1068)
at epicorexpert.EpicoreJFrame.checkConfig(EpicoreJFrame.java:1076)
at epicorexpert.EpicoreJFrame.<init>(EpicoreJFrame.java:94)
What probably-obvious issue am I overlooking? Thanks.
Edit: Why is this being marked as a duplicate question and suggesting a redirect for the thread on what NullPointerExceptions are? I understand what they are and how they're typically resolved. That's not what I'm asking here; this is specifically about the ClassLoader and File objects and why I'm getting NPEs from them.

getResource returns null if the file is not found! That's most probably the cause of your NullPointerException!

Related

FileInputStream is not found even though the file exists [duplicate]

This question already has answers here:
Using FileReader causes a compiler error "unhandled exception type FileNotFoundException"
(7 answers)
Unhandled exception: FileNotFoundException
(5 answers)
Closed 5 years ago.
I am trying to integrate Firebase with my Java Spring web application what runs on server and it give an error:
Unhandled exception: java.io.FileNotFoundException"
The file is exists in the directory:
FileInputStream serviceAccount = new FileInputStream("C:\Users\My Name\Downloads\Projectname\words.txt");
I run a bunch of prints when I just used File where it exists, its readable, the full file path or whatever is the exact same as the file path in the FileInputStream but nothing is working. i cant use a try catch because Firebase doesn't allow it or something. At this point I don't know what to do.
As mentioned in the proposed duplicate, it's likely that your problem is that you need to declare the possible exception by adding throws FileNotFoundException to your method (and all methods that call it). See Using FileReader causes a compiler error "unhandled exception type FileNotFoundException"
The code that you posted above also gives an error illegal escape character at compile time (because backslash is used in Java for representing special characters such as newline \n), which seems to be unrelated to the current problem, but you can fix it by replacing each single backslash with two backslashes as follows:
FileInputStream serviceAccount = new FileInputStream("C:\\Users\\My Name\\Downloads\\Projectname\\words.txt");
When you use path separator, you must remember use \ or / correctly. You should change it to
"C:/Users/My Name/Downloads/Projectname/words.txt"
in Java program.

NoSuchFileException When reading input file [duplicate]

This question already has answers here:
Java Paths.get .... readAllBytes(path)) not working with relative path
(2 answers)
Java isn't getting the file in the source code when compiled
(2 answers)
Closed 5 years ago.
I have an input file data, name input.dat which is stored in the src/main/resources. When I tried to read from this input file as follows:
String[] lines = Files.readAllLines(new File("input.dat").toPath()).toArray(new String[0]);
I received the following exception:
java.nio.file.NoSuchFileException: input.dat
Can anyone help me with what did I do wrong here? Thank you in advance!
The java file you are running is probably not in the same directory as the file input.dat.
When referencing the file in your Java code include the relative path to it. If the java file that you are running is in src/main then the relative path would be resources/input.dat.
In that case, your code would look like this:
String[] lines = Files.readAllLines(new File("resources/input.dat").toPath()).toArray(new String[0]);
Hope this helped you and if you have any further questions please feel free to post a comment below!
Replace input.dat with the exact path of input.dat. Such as C:/Users/Soe/Desktop/input.dat

getResourceAsStream() doesn't read nothing [duplicate]

This question already has answers here:
getResourceAsStream returning null
(1 answer)
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I'm joking with a java trying to program a game, I'm not going to define useless details, the program works, but it works only if I get it from the point where I developed it (Netbeans), but if I try to get it started Jar nothing, I read on the internet that to access files, such as images or txt files, you have to use the Class.class.getResourceAsStream (path), but the latter does not work from starting it from the jar, in fact or me From a NullPointerException or goes smooth, but does not load anything.
Disappeared I would explain the structure of my project and show you my code:
List build
-build
- classes
- mario
-all the package and the file example: crediti/ringraziamenti.txt
List dist
-dist
-jarFile
-mario
-all the package and the file example: crediti/ringraziamenti.txt
-meta inf...
List java
-src
-mario
- all the package and the file example: crediti/ringraziamenti.txt
my code is:
InputStream io =(getClass().getClassLoader().getResourceAsStream("mario/crediti/ringraziamenti.txt"));
BufferedReader br = new BufferedReader(new InputStreamReader(io));
String temp = "";
while((temp = br.readLine())== null){
System.out.println(""+temp);
}
Specify a resource folder, put your files there. Assuming you have structure:
-src
-mario
- all the package and the file example:
crediti/ringraziamenti.txt
add the resource folder on the same level as your packages, move your files there and try:
InputStream io =(getClass().getClassLoader().getResourceAsStream("/crediti/ringraziamenti.txt"));
Fix your code as follows:
Put a slash in front of the path in the getResourceAsStream call, otherwise it will start searching from the package of the current class.
In the while loop, compare != null rather than == null - you want the loop to continue running as long as there lines of text, not as long as there are no lines of text.
InputStream io =(getClass().getClassLoader().getResourceAsStream("/mario/crediti/ringraziamenti.txt"));
BufferedReader br = new BufferedReader(new InputStreamReader(io));
String temp;
while((temp = br.readLine()) != null){
System.out.println(""+temp);
}

Can't find file error handling [duplicate]

This question already has answers here:
How to Check Path is existing or not in java?
(3 answers)
Closed 7 years ago.
Is there a particular way on how to handle errors if my FileInputStream cannot find the inputted file name in its directory? I'm just trying to make it so if my program can't find the file that was typed it'd print an error stating "file doesn't exist"
EDIT: Left out info. Hoping to let users reinput the file name.
Should be as simple as this
try {
<your code>
} catch(FileNotFoundException e) {
e.printStackTrace();
}
The catch does not end your program, you can easily put a loop around the whole block and try it with a different file name each time.
Nevertheless it would be better to test if the file exists, before you try to open it.
new File("filename").exits()

Java exporting images with runnable jar getClass().getClassLoader().getResource("path") returns null [duplicate]

This question already has answers here:
getClass().getResource() always returning null
(5 answers)
Closed 8 years ago.
I am trying to export an image inside my runnable jar. After some research i have come across this method:
ImageIO.read(getClass().getClassLoader().getResource("image path"));
After following several response and looking at the API, i have attempted this myself. My current directory set up is as follows:
This is my code:
cherryImg = ImageIO.read(getClass().getClassLoader().getResource("/res/cherry.png"));
which is being called from the Snake.java source file.
This is the error message:
Exception in thread "main" java.lang.IllegalArgumentException: input == null!
at javax.imageio.ImageIO.read(Unknown Source)
at cje.chris.edwards.snake.game.Snake.<init>(Snake.java:51)
at cje.chris.edwards.snake.game.Snake.main(Snake.java:156)
Snake.java:51 is the line of code posted above. I understand this is because it cannot find the resource, what am i doing wrong? I have added the res folder to my build path.
I have also tried:
cherryImg = ImageIO.read(getClass().getClassLoader().getResource("res/cherry.png"));
This produces the same error message.
Answer:
cherryImg = ImageIO.read(getClass().getClassLoader().getResource("cherry.png"));
Thanks.
I think your problem is the leading "/"
"/res/cherry.png"
Will make it an absolute path (from your root of your drive) not a relative path from your starting from the root of your jar
Making it "res/cherry.png" should work

Categories

Resources