八卦阵 发表于 2023-4-13 21:47:59

java 处理常量字符串过长 & springboot 项目读取 resouces 文件夹下的文件

长字符串起因


[*]项目里面有一长串的加密字符串(最长的万多个字符),需要拼接作为参数发送给第三方。
https://img2023.cnblogs.com/blog/2138456/202304/2138456-20230413211746000-2114736809.png

[*]如果我们使用 枚举 定义的话,idea 编译的时候就会出现编译报错
Error: java:常量字符串过长https://img2023.cnblogs.com/blog/2138456/202304/2138456-20230413211757616-1873639904.png
解决想法


[*]网上还有一个说法,说是编译器问题,修改 idea 工具的编译为 eclipse 即可。
[*]但是结果我仍然不满意,所以我决定把他放在文件中,然后需要的时候读取出来即可。
[*]所以,我就把字符串放到了 resources 的某个 txt 文件下,然后再从文件中读取出来
https://img2023.cnblogs.com/blog/2138456/202304/2138456-20230413211811909-966545396.png
遇到的问题


[*]在 spring boot 项目中,尝试了好多次读取 resources 下的 payload.txt 文件一直失败。
[*]报错一直是该文件不存在
一开始使用的是 hutool util 工具类去读取,但是不成功。
String filePath = "payload.txt";
String contentString = FileUtil.readUtf8String(Thread.currentThread().getContextClassLoader().getResource("").getPath() + filePath);

[*]可以看到我的 target 编译后的文件里面确实是存在这个文件的。
https://img2023.cnblogs.com/blog/2138456/202304/2138456-20230413211841073-233185215.png
最终解决办法

// 先转为流
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/本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须在文章页面给出原文链接,否则保留追究法律责任的权利。
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
页: [1]
查看完整版本: java 处理常量字符串过长 & springboot 项目读取 resouces 文件夹下的文件