// 获取对象的绝对路径 public static String realpath(Object obj) throws URISyntaxException { return new File(obj.getClass().getResource("").toURI()).getAbsolutePath(); }
一般情况下不需要直接使用绝对路径,使用流就可以了,this.getClass().getResourceAsStream(filename)。
如果要获取项目的根路径,把代码中obj.getClass()换成obj.getClass().getClassLoader()就可以了。
System.getProperty("user.dir") 用户的当前工作目录,这个应该和环境有关系,在eclipse中是src的上层目录。
其他信息自己看JDK API就明白了。
/** * 对象所在目录的绝对路径,也就是包的绝对路径 * * @param obj * Object * * @return String */ public static String getClassPath(Object obj) throws URISyntaxException { return new File(obj.getClass().getResource("").toURI()) .getAbsolutePath(); } /** * 获取当前项目的根路径(绝对路径) * * @param obj * Object * * @return String */ public static String getProjectPath(Object obj) throws URISyntaxException { return new File(obj.getClass().getClassLoader().getResource("").toURI()) .getAbsolutePath(); }