首页 > 编程语言 > 详细

SpringBoot 读取 resource 下的文件

时间:2020-03-15 00:16:39      阅读:60      评论:0      收藏:0      [点我收藏+]

在传统 war 包中,因为 tomcat 中保存的是解压后的文件,所以可以根据绝对路径的方式

获取绝对路径的方法是

this.getClass().getResource("/").getPath();

读取文件

但是在 SpringBoot 项目中不行,由于文件在 jar 包中,直接读会抛出java.io.FileNotFoundException

因此我们可以用以下几种方式

InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("aaa.txt");

InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("ala.txt");

// ClassPathResource是Spring的类
InputStream inputStream = new ClassPathResource("aaa.txt").getInputStream();

将InputStream转成String

读到 InputStream 后我们需要将其转换成 String,这个选择也比较多,以下几种方法皆可

方法1:使用InputStreamread(byte[] b),一次性读完

byte[] bytes = new byte[0];
bytes = new byte[inputStream.available()];
inputStream.read(bytes); // 将流保存在bytes中
String str = new String(bytes);

方法2:使用BufferedReaderreadLine(),按行读取

StringBuilder sb = new StringBuilder();
String line;

BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
while ((line = br.readLine()) != null) {
    sb.append(line);
}
String str = sb.toString();

方法3:使用InputStreamread(byte[] b)配合ByteArrayOutputStream,每次读取固定大小

ByteArrayOutputStream result = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) != -1) {
    result.write(buffer, 0, length);
}
String str = result.toString(StandardCharsets.UTF_8.name());

方法4:使用 Google Guava

String str = CharStreams.toString(new InputStreamReader(inputStream, StandardCharsets.UTF_8));

读取properties

同理,properties 配置也不能直接读取。但我们不必将其转换成 String 了,可以有以下两种方式

方法1

ResourceBundle bundle = ResourceBundle.getBundle("application");
String port = bundle.getString("server.port");

方法2

Properties properties = new Properties();
properties.load(inputStream); // 上面的3种获取流方法都可以
String port = properties.getProperty("server.port");

SpringBoot 读取 resource 下的文件

原文:https://www.cnblogs.com/n031/p/12495331.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!