java中文件路径分为关于绝对路径和相对路径,下面简要总结下常用获取文件路径的方法:
测试环境:
elipse: 3.6.2 Helios Service Release 2
JDK:1.7.0_17
测试代码path:/minaTest/src/cn/mina/demo/JavaPathTest.java
测试代码location:D:\JavaEE\workspace\minaTest\src\cn\mina\demo\JavaPathTest.java
1.通过File文件系统:
File directory = new File("");//参数为空
String courseFile = directory.getCanonicalPath() ;
System.out.println(courseFile);
结果:
D:\JavaEE\workspace\minaTest
2.通过class文件获取class path路径 :
File f = new File(JavaPathTest.class.getClass().getResource("/").getPath());
System.out.println(f);
结果:
D:\JavaEE\workspace\minaTest\bin
注:File f = new File(this.getClass().getResource("").getPath()); 会导致空指针异常。
3.通过ClassLoader文件获取class path路径 :
String path=ClassLoader.getSystemResource("selected.txt").getFile();
System.out.println(path);
结果:
/D:/JavaEE/workspace/minaTest/bin/selected.txt
获取当前工程src目录下selected.txt文件的路径
注:System.out.println( JavaPathTest.class.getClass().getClassLoader().getResource("selected.txt"));
会出现NPE异常。
4.通过系统属性user.dir:
String path=System.getProperty("user.dir");
System.out.println(path);
结果:
5.通过系统属性java.class.path:
String path=System.getProperty("java.class.path");
System.out.println(path);
结果:
6.获取jar包父目录路径
public static void main(String[] args) {
String path=getPath();
System.out.println(path);
}
public static String getPath() {
URL url = JavaPathTest.class.getProtectionDomain().getCodeSource().getLocation();
String filePath = null;
try {
filePath = URLDecoder.decode(url.getPath(), "utf-8");// 转化为utf-8编码
} catch (Exception e) {
e.printStackTrace();
}
if (filePath.endsWith(".jar")) {// 可执行jar包运行的结果里包含".jar"
// 截取路径中的jar包名
filePath = filePath.substring(0, filePath.lastIndexOf("/") + 1);
}
File file = new File(filePath);
// /If this abstract pathname is already absolute, then the pathname
// string is simply returned as if by the getPath method. If this
// abstract pathname is the empty abstract pathname then the pathname
// string of the current user directory, which is named by the system
// property user.dir, is returned.
filePath = file.getAbsolutePath();//得到windows下的正确路径
return filePath;
}
结果:
在class方式中,显示bin路径:D:\JavaEE\workspace\minaTest\bin
在jar运行方式中,显示jar所在的路径(测试中jar包位置D:\jtest\pathTest.jar):D:\jtest
注:该方式在程序被打成jar包后,获取程序相关配置文件时相当有用,该方式是通过自测的、获取jar位置的唯一方式(可能有其他更加简单方式吧,但目前没找到)。