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