java获取当前执行文件的路径

需要知道执行jar包时,jar包所在的路径。

开始使用了

p.getClass().getResource("/").getPath();

结果在IDE里面使用是好的,但是在命令行中执行时,会报NullPointerException错误。

接着尝试使用另一种方式,

File f = new File("");
String cf = null;
try {
     cf = f.getCanonicalPath();
} catch (IOException e) {
     e.printStackTrace();
}
System.out.println(cf);

成功。

原文地址:https://www.cnblogs.com/starRebel/p/5156828.html