我对 java 相当陌生,我正在尝试查找 LINUX 路径中指定的文件是否存在。
private void validateFilePath(String filePath) {
File dir = new File(filePath);
if(dir.exists()){
System.out.println("File exists in the path " + dir);
setTARGET_IMG_DIR("filePath");
return;
}else{
System.out.println("File does not exists in the path: " + dir);
return;
}
}
如果我像这样给出从我的根开始的绝对路径,则 dir.exists 工作正常
/Users/yv/Documents/Eclipse-workspace/InputParser/bin/test.txt
但是如果我给出像这样的相对路径
test.txt
或 /InputParser/bin/test.txt
它说文件不存在。
我计划创建该项目的 jar,因此这应该适用于相对路径(同一目录中的文件)和来自根目录的绝对路径。我该如何处理这个问题?
是否可以从根目录搜索该文件的绝对路径并将其附加到文件名中?
最佳答案
Eclipse 通常在项目目录设置为 user.dir
的情况下运行,这是执行的基目录。所以如果绝对路径是:
/Users/yv/Documents/Eclipse-workspace/InputParser/bin/test.txt
那么相对路径将是:
bin/test.txt
您可以通过从 Java 系统属性获取 user.dir
属性来仔细检查工作目录。有关 Java 系统属性的更多信息 check the documentation .
关于java - 尝试查找给定路径中是否存在文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12789780/