/**
* 获取项目执行时候的根路径
*/
public class MyUrlDemo {
public static void main(String[] args) throws Exception {
MyUrlDemo muDemo = new MyUrlDemo();
muDemo.showURL();
}
public void showURL() throws IOException {
// 第1种:
File directory = new File("");// 参数为空
String courseFile = directory.getCanonicalPath();
System.out.println("path1: " + courseFile);
// 第2种:
System.out.println("path2:" + System.getProperty("user.dir"));
}
}
注意:这里很关键 这里很关键 这里很关键


将代码打成jar








测试:
D:\hangyi\ycwlkj\out\artifacts\test_jar>java -jar test.jar
path1: D:\hangyi\ycwlkj\out\artifacts\test_jar
path2:D:\hangyi\ycwlkj\out\artifacts\test_jar
C:\>cd C:\Users\Administrator\Desktop
C:\Users\Administrator\Desktop>java -jar D:\hangyi\ycwlkj\out\artifacts\test_jar\test.jar
path1: C:\Users\Administrator\Desktop
path2:C:\Users\Administrator\Desktop
本文介绍了一种在Java项目中获取项目执行时根路径的方法,通过两种方式演示了如何在不同环境下获取当前项目的根目录路径,对于打包成jar文件运行的项目特别有用。
4832

被折叠的 条评论
为什么被折叠?



