長字串起因
- 專案里面有一長串的加密字串(最長的萬多個字符),需要拼接作為引數發送給第三方,

- 如果我們使用 列舉 定義的話,idea 編譯的時候就會出現編譯報錯
Error: java:常量字串過長

解決想法
-
網上還有一個說法,說是編譯器問題,修改 idea 工具的編譯為 eclipse 即可,
-
但是結果我仍然不滿意,所以我決定把他放在檔案中,然后需要的時候讀取出來即可,
-
所以,我就把字串放到了 resources 的某個 txt 檔案下,然后再從檔案中讀取出來

遇到的問題
- 在 spring boot 專案中,嘗試了好多次讀取 resources 下的 payload.txt 檔案一直失敗,
- 報錯一直是該檔案不存在
一開始使用的是 hutool util 工具類去讀取,但是不成功,
String filePath = "payload.txt";
String contentString = FileUtil.readUtf8String(Thread.currentThread().getContextClassLoader().getResource("").getPath() + filePath);
- 可以看到我的 target 編譯后的檔案里面確實是存在這個檔案的,

最終解決辦法
// 先轉為流
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(path);
// 再把流轉為 String
String content = new BufferedReader(new InputStreamReader(inputStream))
.lines().collect(Collectors.joining("\n"));
- 封裝代碼
public final class ClassPathResourceReader {
/**
* path:檔案路徑
* @since JDK 1.8
*/
private final String path;
/**
* content:檔案內容
* @since JDK 1.6
*/
private String content;
public ClassPathResourceReader(String path) {
this.path = path;
}
public String getContent() {
if (content == null) {
try {
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(path);
if (inputStream!=null) {
content = new BufferedReader(new InputStreamReader(inputStream))
.lines().collect(Collectors.joining("\n"));
}else {
throw new RuntimeException("創建 lookLike-app 受眾出現例外:File not exist");
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return content;
}
}
這樣相當于做了個本地快取,就不用每次都去讀取檔案了,性能嘎嘎快,
- 代碼呼叫
String content = new ClassPathResourceReader("payload.txt").getContent();
作者:天下沒有收費的bug
出處:https://www.cnblogs.com/LoveBB/
本文著作權歸作者和博客園共有,歡迎轉載,但未經作者同意必須在文章頁面給出原文鏈接,否則保留追究法律責任的權利,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/549952.html
標籤:Java
上一篇:OkHttp Address already in use: no further information例外
下一篇:linux環境下安裝Docker
