问题
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.
回答1:
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()
回答2:
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.
回答3:
You can use FileInputStream
only when you actually have a file on the computer's filesystem. When you package your text file in the jar file for your program, it is not a file in the filesystem. It is an entry inside the jar file.
The good news is that it is even easier, in Java, to access the file this way: it is in your classpath, so you can use getResourceAsStream().
InputStream stream = getClass().getResourceAsStream("abc.txt");
If you have your classpath set up correctly, this will work regardless of whether it is a file in a directory (such as during development), or an entry in a jar file (such as when released).
回答4:
It's because your working directory will probably be different under the two environments. Try adding the line
System.out.println(new File("abc.txt").getAbsolutePath());
to see where it is actually looking for the file.
回答5:
Maybe not the most elegant but this is how you can cover all the options in Scala
def loadFile(path: String) = {
val f = new File(path)
if (f.exists) {
loadFileFromPath(path)
} else {
val r = Try {
val in = ClassLoader.getSystemResourceAsStream(path)
new InputStreamReader(in)
}.getOrElse{
val in = getClass.getResourceAsStream(s"/$path")
new InputStreamReader(in)
}
loadFileFromInputStream(r)
}
}
来源:https://stackoverflow.com/questions/41762124/filenotfoundexception-while-running-as-a-jar