SpringBoot读取resource中的文件
在传统 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:使用InputStream
的read(byte[] b)
,一次性读完
byte[] bytes = new byte[0];
bytes = new byte[inputStream.available()];
inputStream.read(bytes); // 将流保存在bytes中
String str = new String(bytes);
方法2:使用BufferedReader
的readLine()
,按行读取
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:使用InputStream
的read(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");
方法3
Properties properties = new Properties();
try {
properties = PropertiesLoaderUtils.loadAllProperties("application.properties");
String port = properties.getProperty("server.port");
} catch (IOException e) {
e.printStackTrace();
}
一些配置文件因为很多人在里面修改,可能导致编码乱七八糟。遇到这种情况,可以在getProperty时这样写避免乱码
String port = new String(properties.getProperty("server.port").getBytes("iso-8859-1"), "utf-8");