简体   繁体   English

Eclipse中的Java文件相对路径

[英]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. 该代码可以工作,但只能在eclipse中编译和运行良好。 But when i export it as as runnable jar file i get an error, that it cannot locate licenca.txt 但是当我将其导出为可运行的jar文件时,出现错误,无法找到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. 我尝试使用扫描仪功能,结果仍然相同,它可以在Eclipse中使用,但在导出时不起作用。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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