1、读取一个文件,并替换其中指定的字符串为特定字符串

本文介绍了如何读取一个文件,并利用正则表达式进行精准匹配和替换操作。在处理test.txt文件时,将所有精确匹配的abc字符串替换为123,避免了abcd这样的部分匹配。同时探讨了在不使用库函数的情况下,通过KMP算法实现字符串替换的可能性。
import java.io.*;
public class readFile {
	public static void main(String[] args){
		StringBuffer sb = new StringBuffer();
		String text = null;
		BufferedReader br = null;
		String ss = null;
	    File f = new File("d:\\findit.txt");
	    try{
	    	FileInputStream fis = new FileInputStream(f);
	    	InputStreamReader isr = new InputStreamReader(fis);
	    	br = new BufferedReader(isr);
	    	while((text=br.readLine()) != null){
	    		ss = text.replace("abc","123");
	    		sb = sb.append(ss).append(System.getProperty("line.separator"));
	    	}
	    }catch(FileNotFoundException e){
	    	e.printStackTrace();
	    }catch(IOException e){
	    	e.printStackTrace();
	    }finally{
	    	try{
	    		if(br != null)
	    			br.close();
	    	}catch(IOException e){
	    		e.printStackTrace();
	         }
	    }
	     System.out.println(sb.toString());
	     System.out.println("-------------------------------");
	     System.out.println(sb.toString());
	    }
### Java 实现文件字符串替换的示例 在 Java 中,可以通过多种方式实现文件字符串替换。以下是使用 `java.nio.file` 包中的类来读取文件内容、替换特定字符串写回文件的完整示例[^4]。 ```java import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class FileStringReplacer { public static void replaceStringInFile(String filePath, String target, String replacement) throws IOException { // 获取文件路径 Path path = Paths.get(filePath); // 读取文件内容为字符串 String content = new String(Files.readAllBytes(path)); // 替换目标字符串为目标替换字符串 content = content.replace(target, replacement); // 将修改后的内容写回文件 Files.write(path, content.getBytes()); } public static void main(String[] args) { try { String filePath = "example.txt"; // 文件路径 String target = "oldString"; // 要替换字符串 String replacement = "newString"; // 替换后的字符串 replaceStringInFile(filePath, target, replacement); System.out.println("字符串替换完成!"); } catch (IOException e) { e.printStackTrace(); } } } ``` 此代码首先通过 `Files.readAllBytes` 方法将整个文件读取为字节数组,将其转换为字符串。然后使用 `String.replace` 方法替换指定字符串。最后,通过 `Files.write` 方法将修改后的内容写回文件[^5]。 ### 注意事项 - 确保文件路径正确,且程序具有对文件的读写权限。 - 如果文件较大,这种方法可能会消耗较多内存,因为整个文件内容会被加载到内存中。对于大文件,建议使用流式处理以减少内存占用[^6]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值