简体   繁体   中英

java file relative path in eclipse

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:

错误

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.

发生这种情况是因为您的文件是作为jar文件的一部分导出的,因此,要创建jar文件,请尝试使用antmaven或其他方法,或者将文件与jar一起手动复制到目录中,它称为start directory

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM