I'm trying to open a resource in my Java application by calling MainClass.class.getResource("/Resources/file.extension") and passing it to File's constructor with getPath(). Next, when I initialize a new FileInputStream with the File, I get a FileNotFoundException. The complete stack trace looks this.
java.io.FileNotFoundException: E:\user\Documents\NetBeansProjects\Project name\build\classes\Resources\file.csv (The system cannot find the path specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at my.secret.project.MainClass.main(MainClass.java:27)
Here's my code.
File file = new File(MainClass.class.getResource("/Resources/file.extension").getPath());
...
InputStream in = new FileInputStream(file);
Your whole code can be replaced with simple:
InputStream in = MainClass.class.getResourceAsStream("/Resources/file.extension");
No need to use File. In fact the file on your CLASSPATH might be pointing to some location inside JAR/WAR, which definitely won't work. Have a loot at Class.getResourceAsStream() for details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With