打包之后读取资源路径出错,找不到资源
假设要读db目录下的某个sql文件,项目没有打包时,通过File类根据src/main/resources/db/xx.sql可以读到具体文件。打包之后这种方法就会找不到指定的资源路径,会报出路径错误找不到文件。
这里自定义一个工具类
public class DbInitConfig {
/**
* 获取jar包中文件路径
*/
public String getFilePath(String fileName) {
// substring(1)去掉最前面的一个盘符号"/"
return DbInitConfig.class.getClassLoader().getResource(fileName).getPath().substring(1);
}
public void getPath() {
String caPath = getFilePath("db/ca.sql");
System.out.println(caPath);
}
}
这种方式读取到的就是编译后项目中资源的路径,打包之后读到也是jar包中的资源路径。