Java 文件内容修改(一)

遇到一个需求,需要修改文件中的内容,查找资料发现如下工具类:

原链接:点击打开链接

/**
	 * 修改文件内容
	 * 
	 * @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已被修改成新的内容

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值