上一篇博客 Java 文件内容修改(一)点击打开链接 中修改文件内容的方法,当文件出现换行时就会有错误。错误结果如下:
运行前文件内容:
运行后:
发现内容缺少。
又发现了另外一种方法:
/**
* 文件内容替换
* @param filePath
* @param oldstr
* @param newStr
*/
private static void autoReplace(String filePath, String oldstr, String newStr) {
File file = new File(filePath);
Long fileLength = file.length();
byte[] fileContext = new byte[fileLength.intValue()];
FileInputStream in = null;
PrintWriter out = null;
try {
in = new FileInputStream(filePath);
in.read(fileContext);
// 避免出现中文乱码
String str = new String(fileContext, "utf-8");
str = str.replace(oldstr, newStr);
out = new PrintWriter(filePath);
out.write(str);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
out.flush();
out.close();
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
这个不管文件内容是怎样,都可以实现,还可以设置编码集,避免中文乱码。
测试:
运行前文件内容:
扫描二维码关注公众号,回复:
2500524 查看本文章
运行后文件内容: