Eclipse中的java文件相对路径

Eclipse中的java文件相对路径

本文介绍了Eclipse中的java文件相对路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

三天我试图弄清楚如何使用相对文件路径读取文件。在日食这编译和工作很好,但是当我出口的应用程序。它说,它无法找到该文件。这里是截图和我工作的代码。

这个代码可以工作,但只有在eclipse中,它编译和完成工作。但是,当我出口作为可运行jar文件,我得到一个错误,它无法找到licenca.txt

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




$ p
$ b $ p这里是我的项目文件的截图





我曾尝试使用扫描仪功能,仍然是相同的结果,它在日食,但不在出口工作。这里是错误信息:



解决方案

如果你把这个文件放到类路径中,它会起作用的。



更改您的代码:

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

试试看。


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

files http://img207.imageshack.us/img207/5317/63432445.png

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:

error http://img98.imageshack.us/img98/1771/greskaa.png

解决方案

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.

这篇关于Eclipse中的java文件相对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 17:56