简体   繁体   中英

How get absolute path to <project>\taget folder

I need to get an absolute path to <project>/target folder. I use the following code:

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

It returns the path like /E:/java/main/target/classes/ But I need to get /E:/java/main/target/

How should I set a value in getResource() ?

In my solution I can not use System.getProperty("user.dir"); for some reason.

The following line will locate you to the base directory, where are the src , resources and target folders located:

System.getProperty("user.dir");

It is the directory, where the JVM was started and those properties are described at System Properties . The full search would look like:

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"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM