How to locate the Path of the current project directory in Java (IDE)?

前端 未结 9 1380
梦如初夏
梦如初夏 2020-11-28 21:46

I am trying to locate the path of the current running/debugged project programmatically in Java, I looked in Google and what I found was System.getProperty(\"user.id\"

相关标签:
9条回答
  • 2020-11-28 22:25

    This is the new way to do it:

    Path root = FileSystems.getDefault().getPath("").toAbsolutePath();
    Path filePath = Paths.get(root.toString(),"src", "main", "resources", fileName);
    

    Or even better:

    Path root = Paths.get(".").normalize().toAbsolutePath();
    

    But I would take it one step further:

    public String getUsersProjectRootDirectory() {
        String envRootDir = System.getProperty("user.dir");
        Path rootDIr = Paths.get(".").normalize().toAbsolutePath();
        if ( rootDir.startsWith(envRootDir) ) {
            return rootDir;
        } else {
            throw new RuntimeException("Root dir not found in user directory.");
        }
    }
    
    0 讨论(0)
  • 2020-11-28 22:27
    File currDir = new File(".");
    String path = currDir.getAbsolutePath();
    System.out.println(path);
    

    This will print . at the end. To remove, simply truncate the string by one char e.g.:

    File currDir = new File(".");
    String path = currDir.getAbsolutePath();
    path = path.substring(0, path.length()-1);
    System.out.println(path);
    
    0 讨论(0)
  • 2020-11-28 22:29

    This is a code snippet to retrieve the path of the current running web application project in java.

    public String getPath() throws UnsupportedEncodingException {
    
        String path = this.getClass().getClassLoader().getResource("").getPath();
        String fullPath = URLDecoder.decode(path, "UTF-8");
        String pathArr[] = fullPath.split("/WEB-INF/classes/");
        System.out.println(fullPath);
        System.out.println(pathArr[0]);
        fullPath = pathArr[0];
    
        return fullPath;
    
    }
    

    Source: https://dzone.com/articles/get-current-web-application

    0 讨论(0)
提交回复
热议问题