以jar运行时出现FileNotFoundException

Sub*_*jit 6 java jar filenotfoundexception

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

作为jar运行时抛出FileNotFoundExceptionn。为什么呢 通常,它可以从main方法运行时找到。

Sub*_*jit 3

class MyClass{

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

}
Run Code Online (Sandbox Code Playgroud)

应该使用此代码。文件(在本例中为 abc.txt)应保留在对象引用类位置。这意味着, this.getClass 引用某个文件夹的位置,即 com/myfolder/MyClass.java 文件夹。

所以我们应该将abc.txt保留在com/myfolder这个位置。