Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FileNotFoundException while running as a jar

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.

like image 755
Subhajit Avatar asked Jan 20 '17 11:01

Subhajit


2 Answers

class MyClass{

    InputStream fstream = this.getClass().getResourceAsStream("abc.txt");

}

This code should be used. And the files(in this case abc.txt) should be kept , in the Object references class location. That means , this.getClass refers to the location of some folder i.e, com/myfolder/MyClass.java folder .

So we should keep the abc.txt in com/myfolder this location.

like image 112
Subhajit Avatar answered Sep 29 '22 22:09

Subhajit


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()

like image 44
YCF_L Avatar answered Sep 29 '22 23:09

YCF_L