一、前言
SpringBoot 打成 Jar 包形式运行后 ,resources 目录下文件的读取修改和原来不太一样,网上比较多的是关于读取的方式,修改的几乎没有,终于在 stackoverflow 上找到了正确的打开方式。
二、 读取
public void read(){
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();
}
}
三、 修改
public void write(){
String filePath = new ClassPathResource("sensitiveWords.dat").getPath();
BufferedWriter sensitiveWordsWriter = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(filePath)));
sensitiveWordsWriter.write(newSensitiveWords);
sensitiveWordsWriter.flush();
sensitiveWordsWriter.close();
}