首页
找靠谱产品
找解决方案
找靠谱公司
找案例
找对的人
专家智库
悬赏任务
SAAS
ToB门户
了解全球最新的ToB事件
论坛
潜水/灌水快乐,沉淀知识,认识更多同行。
ToB圈子
加入IT圈,遇到更多同好之人。
微博
Follow
记录
Doing
博客
Blog
文库
业界最专业的IT文库,上传资料也可以赚钱
下载
分享
Share
排行榜
Ranklist
相册
Album
应用中心
qidao123.com ToB IT社区-企服评测·应用市场
»
论坛
›
软件与程序人生
›
程序人生
›
java 处理常量字符串过长 & springboot 项目读取 resouc ...
返回列表
发新帖
java 处理常量字符串过长 & springboot 项目读取 resouces 文件夹下的文件
[复制链接]
发表于 2023-4-13 21:47:59
|
显示全部楼层
|
阅读模式
长字符串起因
项目里面有一长串的
加密
字符串(最长的万多个字符),需要拼接作为参数发送给第三方。
如果我们使用 枚举 定义的话,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();
复制代码
出处:
https://www.cnblogs.com/LoveBB/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须在文章页面给出原文链接,否则保留追究法律责任的权利。
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
本帖子中包含更多资源
您需要
登录
才可以下载或查看,没有账号?
立即注册
×
回复
使用道具
举报
返回列表
八卦阵
+ 我要发帖
登录后关闭弹窗
登录参与点评抽奖 加入IT实名职场社区
去登录
微信订阅号
微信服务号
微信客服(加群)
H5
小程序
快速回复
返回顶部
返回列表