如何获取<project> \ taget文件夹的绝对路径

时间:2019-04-14 13:12:00

标签: java classloader filepath

我需要获取<project>/target文件夹的绝对路径。 我使用以下代码:

Main main = new Main();
String testPath = main.getClass().getResource("").getPath();
System.out.println(testPath);

它返回类似/E:/java/main/target/classes/的路径 但是我需要得到/E:/java/main/target/

如何在getResource()中设置一个值?

在我的解决方案中,由于某些原因,我无法使用System.getProperty("user.dir");

1 个答案:

答案 0 :(得分:0)

以下行将把您定位到基本目录,其中位于srcresourcestarget文件夹中:

System.getProperty("user.dir");

这是启动JVM的目录,这些属性在System Properties中进行了描述。完整搜索如下所示:

final String targetPath = System.getProperty("user.dir");
final File target = Arrays.stream(new File(targetPath).listFiles(File::isDirectory))
    .filter(file -> "target".equals(file.getName()))
    .findAny()
    .orElseThrow(() -> new FileNotFoundException("The target has not been found"));
相关问题