FileNotFoundException while running as a jar

Subhajit picture Subhajit · Jan 20, 2017 · Viewed 11k times · Source

FileInputStream fstream = new FileInputStream("abc.txt")

is throwing a FileNotFoundExceptionn while running as a jar. Why ? Normally it is able to find while running from main method.

Answer

YCF_L picture YCF_L · Jan 20, 2017

If your file is packaged with your jar then you should to get information using getClass().getResource(url):

FileInputStream inputStream = 
new FileInputStream(new File(getClass().getResource(/path/to/your/file/abc.txt).toURI()));

Else you need to create it always in the same path with your jar and you can get it like you do :

src/myJar.jar
src/folder/abc.txt

FileInputStream fstream = new FileInputStream("folder/abc.txt");

You can read here also :

How do I load a file from resource folder? and File loading by getClass().getResource()