private static List<String> readWordFromFile(String path) {
List<String> words;
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(WordFilter.class.getClassLoader().getResourceAsStream(path)));
words = new ArrayList<String>(1200);
for (String buf = ""; (buf = br.readLine()) != null;) {
if (buf == null || buf.trim().equals(""))
continue;
words.add(buf);
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
try {
if (br != null)
br.close();
} catch (IOException e) {
}
}
return words;
}
/**
*功能描述 获取不重复的敏感词列表
* @author FuHang
* @date 2019/8/23
*/
public static List<String> getSensitiveWords() {
List<String> words = readWordFromFile("wd.txt");
ArrayList<String> resultList = new ArrayList<String>();
// 去除文件中的重复数据
for (String item : words) {
if (!resultList.contains(item)) {
resultList.add(item);
}
}
return resultList;
}
/**
*功能描述 修改敏感词列表
* @author FuHang
* @date 2019/8/23
*/
public static void change(String oldStr,String newStr){
try {
Resource resource = new ClassPathResource("wd.txt");
File sourceFile = resource.getFile();
// WordFilter.class.getClassLoader().getResourceAsStream(path)
RandomAccessFile raf = new RandomAccessFile(sourceFile, "rw");
String line;
while (null!=(line=raf.readLine())) {
if(line.contains(oldStr)){
String[] split = line.split(oldStr);
raf.seek(split[0].length());
raf.writeBytes(newStr);
raf.writeBytes(split[1]);
}
}
raf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
*功能描述 添加
* @author FuHang
* @date 2019/8/23
*/
public static boolean addFile(String data) {
RandomAccessFile rFile = null;
try {
Resource resource = new ClassPathResource("wd.txt");
File sourceFile = resource.getFile();
rFile = new RandomAccessFile(sourceFile, "rw");
long point = rFile.length();
// 到达文件尾
rFile.seek(point);
rFile.writeBytes(data + "\r\n");
/*
* rFile.writeUTF(data + "\r\n");
* rFile.writeInt(2);
*/
rFile.close();
} catch (Exception e) {
return false;
}
return true;
}