長(zhǎng)字符串起因
- 項(xiàng)目里面有一長(zhǎng)串的加密字符串(最長(zhǎng)的萬(wàn)多個(gè)字符),需要拼接作為參數(shù)發(fā)送給第三方。
- 如果我們使用 枚舉 定義的話(huà),idea 編譯的時(shí)候就會(huì)出現(xiàn)編譯報(bào)錯(cuò)
Error: java:常量字符串過(guò)長(zhǎng)
解決想法
-
網(wǎng)上還有一個(gè)說(shuō)法,說(shuō)是編譯器問(wèn)題,修改 idea 工具的編譯為 eclipse 即可。
-
但是結(jié)果我仍然不滿(mǎn)意,所以我決定把他放在文件中,然后需要的時(shí)候讀取出來(lái)即可。
-
所以,我就把字符串放到了 resources 的某個(gè) txt 文件下,然后再?gòu)奈募凶x取出來(lái)
遇到的問(wèn)題
- 在 spring boot 項(xiàng)目中,嘗試了好多次讀取 resources 下的 payload.txt 文件一直失敗。
- 報(bào)錯(cuò)一直是該文件不存在
一開(kāi)始使用的是 hutool util 工具類(lèi)去讀取,但是不成功。文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-412564.html
String filePath = "payload.txt";
String contentString = FileUtil.readUtf8String(Thread.currentThread().getContextClassLoader().getResource("").getPath() + filePath);
- 可以看到我的 target 編譯后的文件里面確實(shí)是存在這個(gè)文件的。
最終解決辦法
// 先轉(zhuǎn)為流
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(path);
// 再把流轉(zhuǎn)為 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:文件內(nèi)容
* @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("創(chuàng)建 lookLike-app 受眾出現(xiàn)異常:File not exist");
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return content;
}
}
這樣相當(dāng)于做了個(gè)本地緩存,就不用每次都去讀取文件了,性能嘎嘎快。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-412564.html
- 代碼調(diào)用
String content = new ClassPathResourceReader("payload.txt").getContent();
到了這里,關(guān)于java 處理常量字符串過(guò)長(zhǎng) & springboot 項(xiàng)目讀取 resouces 文件夾下的文件內(nèi)容的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!