我是用maven + spring boot构建的项目。
想获得项目的src/main/resources目录下的一个配置文件,结果却加载不到。
发现根本原因在于定位不到classpath。
比如下面这个代码:
File file=new File("classpath:");
System.out.println(file.getAbsolutePath());
获得的是父项目的绝对路径,这肯定不对。
换一种写法,引号里什么也不写:
File file=new File("");
System.out.println(file.getAbsolutePath());
也是一样的。
网上查了很久没查出来,查了半天才找到解决办法。
第一种办法:
String classpath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
第二种办法:
String classpath = HelloWorld.class.getClassLoader().getResource("").getPath();
两种办法都能解决问题,只是路径的最前面多了一个斜杠,如果在windows系统下,在这样的路径后面拼接上配置文件的路径,有框架无法识别,可以用File类处理一下:
File file = new File(classpath + "fastdfs-client.conf");
System.out.println(file.getAbsolutePath());
此时最前面的斜杠就不见了。