SpringBoot读取Resource下文件的几种方式

ClassPathResource classPathResource = new ClassPathResource("static/test.txt");
InputStream inputStream =classPathResource.getInputStream();
InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("static/test.txt");
InputStream inputStream = this.getClass().getResourceAsStream("/static/test.txt");
File file = ResourceUtils.getFile("classpath:static/test.txt");
InputStream inputStream = new FileInputStream(file);

推荐前三种,因为第四种在打成jar包后会出错,其原因可能是jar包压缩了目标文件而getFile读取错误。

你可能感兴趣的:(Java)