Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetching a resource in Java main method

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);
like image 484
MikkoP Avatar asked Oct 27 '25 02:10

MikkoP


1 Answers

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.

like image 199
Tomasz Nurkiewicz Avatar answered Oct 28 '25 16:10

Tomasz Nurkiewicz