File cannot be accessed after export (Java)

折月煮酒 提交于 2019-12-02 15:43:04

问题


I know that there are many questions like this out there, but so far there have been none that have been of help.

In eclipse, I have a file inside of my project folder ,and I can get it to load using:

 BufferedReader in = new BufferedReader(new FileReader(new File(path)));

When I export the project it will not load the file because it cannot find the file. I have no idea what is going on. Any suggestions? Thanks.


回答1:


If you want to read the file, you have two options.

You Could...

Make sure that the file is in the same directory as the exported jar file and/or the same execution context. This will allow you to use something like BufferedReader in = new BufferedReader(new FileReader(new File("./" + fileName)));

When referencing the file, it need to specify a relative path to the file.

This means you must ensure that the file is copied to the correct location when ever you move the jar file.

You Could...

Embed the file within the jar as an embedded resource. This means that the file becomes part of the jar file. This also means that you can no longer reference it as a File, but need to use Class#getResource or Class#getResourceAsStream, for example...

BufferedReader in = new BufferedReader(
    new InputStreamReader(this.getResourceAsStream("/path/to/resource")));

In order to use this, the file must be placed within the resources directory within your Eclipse project and the directory included within your build path


If you want to be able to write to the file, then you MUST use option one. Embedded resources can not be written to (without a lot of work)



来源:https://stackoverflow.com/questions/25777253/file-cannot-be-accessed-after-export-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!