JAVA中获取项目文件路径

本地运行

public class F{

public void getPath() throws IOException {
        System.out.println("==========getPath()============");
        System.out.println(this.getClass().getClassLoader().getResource("").getPath());
        System.out.println(this.getClass().getClassLoader().getResource(".").getPath());
        //System.out.println(this.getClass().getClassLoader().getResource("/").getPath())    //空指针异常   
    }
    public static void main(String[] args) throws Exception{ 
          System.out.println(Thread.currentThread().getContextClassLoader().getResource(".").getPath());
          System.out.println(Thread.currentThread().getContextClassLoader().getResource("").getPath());
          System.out.println(Thread.currentThread().
                  getContextClassLoader().
                  getResource(""));
         /* System.out.println(Thread.currentThread().
                  getContextClassLoader().
                  getResource("/").
                  getPath());*///空指针异常
          F f=new F();
          f.getPath();      
     } 

}

 

运行结果

/D:/workspace-test/ftp/target/classes/
/D:/workspace-test/ftp/target/classes/
file:/D:/workspace-test/ftp/target/classes/

==========getPath()============
/D:/workspace-test/ftp/target/classes/
/D:/workspace-test/ftp/target/classes/

你可能感兴趣的:(Java)