RandomAccessFile 替换文件内容 并写入
来源:互联网 发布:公安局 网络皮条客 编辑:程序博客网 时间:2024/05/16 04:42
private static boolean modifyFileContent(String filePath, String replaceContent, String regex) {
//修改文件内容,写入日期
RandomAccessFile raf = null;
try {
raf = new RandomAccessFile(filePath, "rw");
String line = null;
long lastPoint = 0; //记住上一次的偏移量
while ((line = raf.readLine()) != null) {
final String str = replaceFileContent(line, replaceContent, regex); //读取文件一行,将匹配正则的字符串替换。
final long ponit = raf.getFilePointer();
raf.seek(lastPoint);
raf.writeBytes(str);
lastPoint = ponit; //读取一行,指针指到下一行开头。用作写下一行,偏移量的开始,。
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
raf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return true;
//修改文件内容,写入日期
RandomAccessFile raf = null;
try {
raf = new RandomAccessFile(filePath, "rw");
String line = null;
long lastPoint = 0; //记住上一次的偏移量
while ((line = raf.readLine()) != null) {
final String str = replaceFileContent(line, replaceContent, regex); //读取文件一行,将匹配正则的字符串替换。
final long ponit = raf.getFilePointer();
raf.seek(lastPoint);
raf.writeBytes(str);
lastPoint = ponit; //读取一行,指针指到下一行开头。用作写下一行,偏移量的开始,。
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
raf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return true;
}
/**
*
* <p>替换匹配正则的内容。</p>
*
* @param srcContent 源字符串
* @param replaceContent 替换内容
* @param regex 正则表达式
* @return boolean
*/
private static String replaceFileContent(String srcContent, String replaceContent, String regex) {
final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(srcContent);
final StringBuffer sb = new StringBuffer();
if (matcher.find()) {
matcher.appendReplacement(sb, replaceContent);
}
return sb.toString();
}
0 0
- RandomAccessFile 替换文件内容 并写入
- Java中使用RandomAccessFile向文件最后写入内容
- 在文件指定位置读取和写入内容RandomAccessFile
- 在文件指定位置读取和写入内容RandomAccessFile
- 创建文件并写入内容
- 替换文件中某个字符串并写入新内容(Java代码实现)
- 替换文件中某个字符串并写入新内容(Java代码实现)
- Java RandomAccessFile 随机写入文件
- ASP.NET创建文件并写入内容
- ASP.NET创建文件并写入内容
- asp 新建文件并写入内容
- ASP.NET创建文件并写入内容
- ASP.NET创建文件并写入内容
- ASP.NET创建文件并写入内容
- ASP.NET创建文件并写入内容
- 将JSON内容写入并读取文件
- java创建一个文件并写入内容
- 批量生成文件并写入大量内容
- Unity3D场景搭建5:相机
- 黑马程序员 Thread.start()与Thread.run()有什么区别
- linux shell 中"2>&1"含义
- Tomcat启动分析
- VMware ESXi 中的 CentOS 硬盘扩容
- RandomAccessFile 替换文件内容 并写入
- selenium运行自动化脚本(调试验证通过)
- UVa 834 - Continued Fractions
- 开始
- Node.js入门学习笔记-IDE选择/配置之WebStorm(windows)
- Oracle 创建新用户,并授权
- 【LeetCode】Rotate List
- 黑马程序员 java小总结
- Spring JdbcTemplate 批量插入或更新操作