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:使用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");

方法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");


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM