Java 获取项目路径

public String getCurrentPath(){
        //取得根目录路径  
        String rootPath=getClass().getResource("/").getFile().toString();
        //当前目录路径  
        String currentPath1=getClass().getResource(".").getFile().toString();
        String currentPath2=getClass().getResource("").getFile().toString();
        //当前目录的上级目录路径  
        String parentPath=getClass().getResource("../").getFile().toString();

        return rootPath;

    }

Java 获取项目路径_第1张图片

加上

File file = new File(System.getProperty("user.dir"));
        System.out.println(file);
        // get parent dir
        String parentPath1 = file.getParent();
        System.out.println(parentPath1);

感觉这个很好用,直接获得当前项目路径

        System.out.println(System.getProperty("user.dir"));
        File file = new File(System.getProperty("user.dir"));
        System.out.println(file);
        // get parent dir
        String parentPath1 = file.getParent();
        System.out.println(parentPath1);
        String toolPath = parentPath + "/tool";
        System.out.println(toolPath);
        FileUtil.createFolderIfNotExist(toolPath);
        System.out.println(toolPath);

Java 获取项目路径_第2张图片

Java 获取项目路径_第3张图片

这里加不加/都是可以的

你可能感兴趣的:(Java 获取项目路径)