1、获取编译后的路径target/classes(推荐使用)
Thread.currentThread().getContextClassLoader().getResource("hhh.txt").getPath();
获取的是编译后target/classes下的文件 在这个文件下查找
获取的路径如下
/F:/item/ssm/target/classes/hhh.txt
windows下想要使用的话最好将其改变成分隔符为\的形式,如下
//修改地址格式
public static String getNewPathString(String oldPath){
oldPath=oldPath.substring(1);
String newPath = oldPath=oldPath.replace("/","\\");
return newPath;
}
但是如果存在多系统进行部署的话最好变成如下形式的分隔符,这样的分隔符具有通用性
static final String separator = File.separator;
//修改地址格式
public static String getNewPathString(String oldPath){
oldPath=oldPath.substring(1);
String newPath = oldPath=oldPath.replace("/",separator);
return newPath;
}
2、获取项目根目录
System.getProperty("user.dir")
//获取的路径为F:/item/ssm/
//为项目所在路径
前提是不是web项目 如果是web路径则要注意获取的路径为“tomcat下的bin目录”
特殊注意一点windows下才用反斜杠“\”表示目录 而linux采用正斜杠“/”
同时java中“\”反斜杠代表转义字符一般都用“\”两个反斜杠表示 或者File.separator
推荐使用File.separator