長字元串起因 項目裡面有一長串的加密字元串(最長的萬多個字元),需要拼接作為參數發送給第三方。 如果我們使用 枚舉 定義的話,idea 編譯的時候就會出現編譯報錯 Error: java:常量字元串過長 解決想法 網上還有一個說法,說是編譯器問題,修改 idea 工具的編譯為 eclipse 即可。 ...
長字元串起因
- 項目裡面有一長串的加密字元串(最長的萬多個字元),需要拼接作為參數發送給第三方。
- 如果我們使用 枚舉 定義的話,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/
本文版權歸作者和博客園共有,歡迎轉載,但未經作者同意必須在文章頁面給出原文鏈接,否則保留追究法律責任的權利。