java file relative path in eclipse

回眸只為那壹抹淺笑 提交于 2020-01-14 04:25:07

问题


Three days i was trying to figure out how to read file using relative file path. In eclipse this compiles and works great, but when i export app. It says that it can't find the file. here is the screenshot and code i work on.

This code works, but only in eclipse, it compiles and does job perfectly. But when i export it as as runnable jar file i get an error, that it cannot locate licenca.txt

 BufferedReader in = new BufferedReader(new FileReader(new File("licenca.txt").getPath()));
        String str;
        while ((str = in.readLine()) != null) {
      taLicenca.append(str + "\n");

    }

here is the screenshot of my project files

i have tried use of scanner function, still the same result, it works in eclipse, but doesn't work on export. Here is the error message:


回答1:


I'll bet it'll work if you put that file into the classpath.

Change your code like this:

InputStream is = this.getClass().getClassLoader().getResourceAsStream("licenca.txt");
BufferedReader in = new BufferedReader(new InputStreamReader(is));
String str;
while ((str = in.readLine()) != null) {
    taLicenca.append(str + "\n");
}

Try it and see.




回答2:


It happens because your file is exported as part of jar file, so, for creating jar file try to use ant or maven or semething else, or manually copy your file in directory with with your jar, it calls start directory.



来源:https://stackoverflow.com/questions/11073702/java-file-relative-path-in-eclipse

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