MENU

Java获取项目路径

February 21, 2020 • Read: 758 • 编程之路,Java

Java获取项目路径

1. 利用System获取

System.getProperty("user.dir");
//输出: E:\IDEA\canye365-crawler-demo

2.利用File类

new File("").getCanonicalPath(); // 当前项目路径
//输出: E:\IDEA\canye365-crawler-demo
new File(".").getCanonicalPath(); // 当前项目路径
//输出: E:\IDEA\canye365-crawler-demo
new File("..").getCanonicalPath(); // 当前项目上一级目录的路径
//输出: E:\IDEA
new File("abc").getCanonicalPath(); //当前项目路径中的abc文件夹,事实上并不存在
//输出: E:\IDEA\canye365-crawler-demo\abc 

3. 获取当前工程classes文件夹路径

this.getClass().getResource("/").getPath(); // classes文件夹路径
//输出: /E:/IDEA/canye365-crawler-demo/target/test-classes/
this.getClass().getResource("").getPath(); // 类的具体路径
//输出: /E:/IDEA/canye365-crawler-demo/target/test-classes/cn/canye365/

4.获取当前工程classes文件夹路径

对于maven工程,resources文件夹下的文件会生成到classes文件夹中。

this.getClass().getClassLoader().getResource("123.html").getPath(); //找不到文件会报NullPointerError
//输出: /E:/IDEA/canye365-crawler-demo/target/classes/123.html
this.getClass().getClassLoader().getResource(".").getPath();
//输出: /E:/IDEA/canye365-crawler-demo/target/test-classes/

对于方法3、4,输出的路径最前面有一个/

- - - 结束 - - -
  • 文章标题:Java获取项目路径
  • 文章链接:https://blog.canye365.cn/archives/203.html
  • 版权所有:本文版权归 残夜 所有,转载请注明出处!除特殊注明外 (如有侵权,请 点此联系我 )