Java – 如何在项目中获取文件的正确绝对路径

我的Java项目中的文件夹中有一个XML文件,我想得到它的绝对路径,所以我可以将它作为文件加载以解析它(DOM)。 我不想使用绝对/相对路径,而只想指定文件名,然后获取绝对路径。 我试图用几种不同的方式做到这一点,但是我得到的路径总是缺少一个文件夹名称。

我明白了:

C:\Users\user\workspace\projectName\Input.xml

代替:

 C:\Users\user\workspace\projectName\\**Folder1**\\Input.xml 

 File input = new File(project.getFile("Input.xml").getLocation().toString());` File input = new File(project.getFile("Input.xml").getRawLocation().makeAbsolute().toString()); File input = new File(project.getFile("Input.xml").getLocationURI().getRawPath().toString()); File input = new File(project.getFile("Input.xml").getFullPath().toFile().getAbsolutePath()); 

如何获得包含Folder1的正确路径?

阅读你的问题(你的项目在工作区目录中)我想你在谈论Eclipse中的一个项目。

那么你的应用程序运行到Eclipse的默认目录就是你项目的基础目录。

所以如果你在你的主要运行这样的东西:

 Files.newDirectoryStream(Paths.get(".")) .forEach(path -> { System.out.println(path); System.out.println(path.toFile().getAbsolutePath()); }); 

您应该看到项目中的所有文件和目录。

因此,如果您想要的只是项目运行的绝对路径:

 System.out.println(Paths.get(".").toFile().getAbsolutePath()); 

如果要打开仅指定名称的资源Input.xml ,我建议在目录中移动所需的所有文件并运行如下方法:

  public static File getFileByName(String name, String path) throws IOException { ArrayList files = new ArrayList<>(); Files.newDirectoryStream(Paths.get(path)) .forEach(p -> { if (p.getFileName() .equals(name)) files.add(p.toFile()); }); return files.size() > 0 ? files.get(0) : null; }