遇到一个需求,需要修改文件中的内容,查找资料发现如下工具类:
原链接:点击打开链接
/**
* 修改文件内容
*
* @param fileName
* @param oldstr
* @param newStr
* @return
*/
private static boolean modifyFileContent(String fileName, String oldstr, String newStr) {
RandomAccessFile raf = null;
try {
raf = new RandomAccessFile("D:\\" + fileName, "rw");
String line = null;
// 记住上一次的偏移量
long lastPoint = 0;
while ((line = raf.readLine()) != null) {
// 文件当前偏移量
final long ponit = raf.getFilePointer();
// 查找要替换的内容
if (line.contains(oldstr)) {
String str = line.replace(oldstr, newStr);
System.err.println(str);
raf.seek(lastPoint);
raf.writeBytes(str);
}
lastPoint = ponit;
System.err.println(lastPoint);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
raf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return true;
}
运行结果:
执行前文件内容:
执行后文件内容:
dyy已被修改成新的内容