Java 解析文件路径 - Eclipse 中的“找不到文件”错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19033789/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Resolving File paths - 'File not found' error in Eclipse
提问by Nikhil
My current directory has files registers.xml and MySaxparser.java. But I still get a File not found error when i use new File("register.xml");
我的当前目录有文件 registers.xml 和 MySaxparser.java。但是当我使用 new File("register.xml"); 时,我仍然收到 File not found 错误。
My cwd is : C:\Users\nb\workspaceAndroid\MySaxParser
我的 cwd 是: C:\Users\nb\workspaceAndroid\MySaxParser
Im using Java 1.7 , Eclipse platform on windows
我在 Windows 上使用 Java 1.7,Eclipse 平台
public static void main(String[] args) {
File file1 = new File("register.xml");
if(file1.exists()){
System.out.println("File existed");
}else{
System.out.println("File not found!");
}
System.out.println("Working Directory = " + System.getProperty("user.dir"));
Output:
输出:
File not found!
Working Directory = C:\Users\nb\workspaceAndroid\MySaxParser
I tried the line below whcih didnt work too.
我尝试了下面的行,但也没有用。
File file1 = new File("C:\Users\nb\workspaceAndroid\MySaxParser\register.xml");
采纳答案by Sunil Manheri
Use getClass().getResource() to read a file in the classpath:
使用 getClass().getResource() 读取类路径中的文件:
URL url = getClass().getResource("register.xml");
Complete code:
完整代码:
URL url = getClass().getResource("register.xml");
File file = new File(url.toURI());
回答by Nikhil
The current working directory in Eclipse Java project is different from the directory where the files are kept
Eclipse Java 项目中的当前工作目录与保存文件的目录不同
directory C:\Users\nb\workspaceAndroid\MySaxParser\src
目录 C:\Users\nb\workspaceAndroid\MySaxParser\src
Working dir : C:\Users\nb\workspaceAndroid\MySaxParser
工作目录:C:\Users\nb\workspaceAndroid\MySaxParser
Make sure the file paths are relative to the working directory.
确保文件路径相对于工作目录。