我对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/