Java 实现替换文件的指定内容


//import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/**
 * @title 文件替换
 * @date 2019年6月21日 上午9:46:03
 */
public class ReplaceFile {
	/***
	 * 替换指定文件中的指定内容
	 * 
	 * @param filepath
	 *            文件路径
	 * @param sourceStr
	 *            文件需要替换的内容
	 * @param targetStr
	 *            替换后的内容
	 * @return 替换成功返回true,否则返回false
	 */
	public static boolean replaceFileStr(String filepath, String sourceStr, String targetStr) {
		try {
			FileReader fis = new FileReader(filepath); // 创建文件输入流
//			BufferedReader br = new BufferedReader(fis);
			char[] data = new char[1024]; // 创建缓冲字符数组
			int rn = 0;
			StringBuilder sb = new StringBuilder(); // 创建字符串构建器
			// fis.read(data):将字符读入数组。在某个输入可用、发生 I/O
			// 错误或者已到达流的末尾前,此方法一直阻塞。读取的字符数,如果已到达流的末尾,则返回 -1
			while ((rn = fis.read(data)) > 0) { // 读取文件内容到字符串构建器
				String str = String.valueOf(data, 0, rn);// 把数组转换成字符串
//				System.out.println(str);
				sb.append(str);
			}
			fis.close();// 关闭输入流
			// 从构建器中生成字符串,并替换搜索文本
			String str = sb.toString().replace(sourceStr, targetStr);
			FileWriter fout = new FileWriter(filepath);// 创建文件输出流
			fout.write(str.toCharArray());// 把替换完成的字符串写入文件内
			fout.close();// 关闭输出流

			return true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}

	}
}

 

 

  • 3
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
Java中,你可以使用Swing或JavaFX等GUI库来创建界面,然后利用文件I/O操作来读取和修改文本文件内容。下面是一个简单的例子,展示如何创建一个按钮,当点击时会替换文本文件的第二行内容: ```java import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.charset.StandardCharsets; public class Main { public static void main(String[] args) { // 创建一个新的窗口 JFrame frame = new JFrame("File Replace"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 创建一个面板 JPanel panel = new JPanel(); frame.add(panel); // 创建一个按钮 JButton button = new JButton("Replace File Line"); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String lineToReplace = "New Line Content"; // 要替换成的新内容 try { // 读取原文件 File file = new File("path_to_your_file.txt"); // 替换为你的文件路径 String content = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8).get(1); // 获取第二行(索引从0开始) // 替换第二行 content = content.replaceFirst(content, lineToReplace); // 写回文件 Files.write(file.toPath(), Arrays.asList(content), StandardCharsets.UTF_8); JOptionPane.showMessageDialog(frame, "Line replaced successfully!"); } catch (IOException ex) { JOptionPane.showMessageDialog(frame, "Error replacing line: " + ex.getMessage()); } } }); panel.add(button); frame.pack(); frame.setVisible(true); } } ``` **相关问题:** 1. Java Swing和JavaFX有什么区别?它们各自适合什么样的场景? 2. 在Java中如何处理文件I/O异常,例如`FileNotFoundException`? 3. 如果文件不存在,这个例子应该如何处理?

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

cocosum

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值