使用java代码读取properties文件,在new File的时候突然发现直接使用相对路径不管用了,之前做开发因为业务以及工作内容没有涉及到这块,也没有太关注这方面的东西,这次做一个相对比较全的分析。
1、可以通过类的class文件路径获知当前项目或者编译文件的路径
在Class类里面有这样一个方法
public static void main(String[] args) throwsIOException {//获取当前类class所在的resource路径
System.out.println(TestFilePath.class.getResource("/").getPath());//获取当前类class所在的路径:
System.out.println(TestFilePath.class.getResource("").getPath());
}
View Code
代码输出结果如下,我们可以很明显的知道加载资源文件是需要resource根目录的,一般我们使用带斜杠的
/E:/develop/workspace/selfproject/nutrition/target/test-classes/
/E:/develop/workspace/selfproject/nutrition/target/test-classes/cn/test/
获取这个路径后还要直接拼接资源文件路径,可以直接通过TestFilePath.class.getResource("/request-mapping.properties").getPath()方式获取
2、通过new File("")来确定工程目录(非编译运行文件的目录)
public static void main(String[] args) throwsIOException {
File f= new File("");
System.out.println("空字符file的Path