所以我试图从我的Eclipse项目中的配置文件中读取,但它无法找到该文件。这是我的代码。
public void readConfigFile () {
//URL url = Test.class.getClassLoader().getResource("myfile.txt");
//System.out.println(url.getPath());
URL url = getClass().getResource("/config");
System.out.println(url);
try {
BufferedReader read = new BufferedReader(new FileReader(url.toString()));
//read in values for constants from config file
System.out.println(BASE_URL);
BASE_URL = read.readLine().split("\t")[1];
System.out.println(BASE_URL);
read.close();
}
catch (Exception e)
{
System.out.println("Read from config file failed. Terminating program");
System.out.println(e);
System.exit(1);
}
}
当我跑步时,它会将url
变量打印为:
/用户/ MYNAME /开发/工作区/ New_API / bin中/配置
但是在运行BufferedReader命令时无法找到该文件。我明白了:
Read from config file failed. Terminating program
java.io.FileNotFoundException:
file:/Users/myname/Development/workspace/New_API/bin/config.txt (No such file or directory)
然后,当我转到我的代码的bin目录时,配置文件就在那里。在根bin目录中,遵循URL给出的确切路径。什么弄乱了Eclipse?
答案 0 :(得分:1)
从类加载器获取资源时,您从类路径获取资源,而不是从文件系统获取资源。如果您的应用程序打包为jar,则无法通过File
或FileInputStream
API访问该资源,因为该资源是存档的一部分。相反,您可以像这样访问资源的输入流:
URL url = getClass().getResource("/config");
BufferedReader read = new BufferedReader(new InputStreamReader(url.openStream()));
// more...