一、前言
SpringBoot 打成 Jar 包形式运行后 ,resources 目录下文件的读取修改和 Spring 不太一样,网上比较多的是关于读取的方式,修改的几乎没有,终于在 * 上找到了正确的打开方式。
二、 文件读取
public void read(){
InputStream inputStream = null;
BufferedReader bufferedReader = null;
try {
inputStream= getClass().getClassLoader().getResourceAsStream("sensitiveWords.dat");
bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
String txt;
while ((txt = bufferedReader.readLine()) != null) {
// do more
}
} catch (Exception e) {
log.error("文件不存在", e);
} finally {
bufferedReader.close();
inputStream.close();
}
}
三、 文件修改
public void write(){
File file = new ClassPathResource("sensitiveWords.dat").getFile();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(file));
bufferedWriter.write("data");
bufferedWriter.flush();
bufferedWriter.close();
}