@Test
public void getPath() throws FileNotFoundException {
//获取在resources路径下的配置文件
System.out.println(ResourceUtils.CLASSPATH_URL_PREFIX+"generatorConfig.xml");
//获取项目所在绝对路径
System.out.println("++++++++");
System.out.println(System.getProperty("user.dir"));
//获取classes路径
System.out.println("-------------");
String path = ResourceUtils.getURL("classpath:").getPath();
System.out.println(path);
System.out.println("000000000000");
String conf = Thread.currentThread().getContextClassLoader().getResource("").getPath();
System.out.println(conf);
}
直接读取配置文件
第一种:
ClassPathResource classPathResource = new ClassPathResource("excleTemplate/test.xlsx");
InputStream inputStream =classPathResource.getInputStream();
第二种:
InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("excleTemplate/test.xlsx");
第三种
InputStream inputStream = this.getClass().getResourceAsStream("/excleTemplate/test.xlsx");
第四种
File file = ResourceUtils.getFile("classpath:excleTemplate/test.xlsx");
InputStream inputStream = new FileInputStream(file);
前三种方法在开发环境(IDE中)和生产环境(linux部署成jar包)都可以读取到,第四种只有开发环境 时可以读取到,生产环境读取失败。
推测主要原因是springboot内置tomcat,打包后是一个jar包,无法直接读取jar包中的文件,读取只能通过类加载器读取。
前三种都可以读取到其实殊途同归,直接查看底层代码都是通过类加载器读取文件流,类加载器可以读取jar包中的编译后的class文件,当然也是可以读取jar包中的excle模板了。