获取项目路径的几种方法

Java获取当前项目路径:

  • object.class.getResource()方法获得当前生成的class的绝对路径(此方法在jar包中无效,因为他获得的是生成的class的路径,返回的内容最后包含/)
    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;         
      
       }  
    • 利用System.getProperty()函数获取当前路径,得到项目文件夹的根目录,不带/ 

    例如 项目在 D:workspace estPorjject

    者System.getProperty("user.dir") 返回 D:workspace estPorjject 

    System.out.println(System.getProperty("user.dir"));//user.dir指定了当前的路径   
原文地址:https://www.cnblogs.com/zipon/p/6193529.html