SpringBoot 动态更新 resources 目录的文件

2019-04-18 20:14:05 浏览数 (4)

一、前言

 SpringBoot 打成 Jar 包形式运行后 ,resources 目录下文件的读取修改和原来不太一样,网上比较多的是关于读取的方式,修改的几乎没有,终于在 stackoverflow 上找到了正确的打开方式。

二、 读取

代码语言:javascript复制
        InputStream stream = null;
        BufferedReader bufferedReader = null;
        try {
            stream = getClass().getClassLoader().getResourceAsStream("sensitiveWords.dat");
            bufferedReader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
            String txt;
            while ((txt = bufferedReader.readLine()) != null) {
                set.add(txt);
            }
        } catch (Exception e) {
            log.error("sensitiveWords.dat 文件不存在", e);
        } finally {
            bufferedReader.close();
            stream.close();
        }

三、 修改

代码语言:javascript复制
            String filePath = new ClassPathResource("sensitiveWords.dat").getPath();
            BufferedWriter sensitiveWordsWriter = new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream(filePath)));
            sensitiveWordsWriter.write(newSensitiveWords);
            sensitiveWordsWriter.flush();
            sensitiveWordsWriter.close();

1 人点赞