FileNotFoundException after exporting as .jar file

2019-02-15 10:54发布

问题:

I'm using Eclipse and developing a java application where I use of a local file. The file is inside the project folder, in a subfolder, say "mydata/myfile.txt" When I run the app from eclipse everything works fine, I open a FileInputStream passing "mydata/myfile.txt" as the name and the file is read just fine. But when I export my application as .jar, and try to run it, all I get is a FileNotFoundException in the console.

How can I export the program so that it can run on any computer and be able to access the file? Thank you in advance.

回答1:

When your app is exported as a jar, your config file is not available as a file, since it's wrapped up in the .jar file. Instead you should access it via ClassLoader.getResourceAsStream(). See this SO question for more background info.



回答2:

Maybe this will help you

InputStream in=ClassLoader.getSystemResourceAsStream("your file");