替换文本:将文本文件中的所有src替换为dst

题意:

将文本文件中的所有src替换为dst

方法一:使用String

 1 import java.io.File;
 2 import java.io.FileNotFoundException;
 3 import java.io.PrintWriter;
 4 import java.util.Scanner;
 5 
 6 
 7 public class Demo2 {
 8     public static void main(String[] args) throws FileNotFoundException {
 9         // 使用Scanner处理文本
10         Scanner sc = new Scanner(new File("ddd.txt"));    // 文件可能不存在,所以要声明异常
11         String passage = "";
12         
13         while(sc.hasNextLine()) // 把ddd.txt的内容保存到passage字符串中
14             passage += sc.nextLine() + "\n";    // nextLine()中不包含回车
15         
16         // 把ddd.txt中的src替换为dst
17         String src = "Hello";
18         String dst = "World";
19         passage = passage.replace(src, dst);    // 注意replace()方法的返回值
20         // 使用PrintWriter写入文本
21         PrintWriter pw = new PrintWriter("ddd.txt");
22         pw.print(passage);    // 将替换后的文本写回ddd.txt (覆盖写)
23         
24         pw.close();        // 记得关流,不然数据写不进去
25     }
26 }

 

 

方法二:使用StringBuffer

 1 import java.io.File;
 2 import java.io.FileNotFoundException;
 3 import java.io.PrintWriter;
 4 import java.util.Scanner;
 5 
 6 
 7 public class Demo {
 8     public static void main(String[] args) throws FileNotFoundException {
 9         // 使用Scanner处理文本
10         Scanner sc = new Scanner(new File("ddd.txt"));    // 文件可能不存在,所以要声明异常
11         StringBuffer sb = new StringBuffer();    
12         while(sc.hasNextLine()) {
13             sb.append(sc.nextLine());    // nextLine()中不包含回车
14             sb.append('\n');
15         }
16         
17         // 把sb中的src替换为dst
18         String src = "static";
19         String dst = "Hello";
20         int index = sb.indexOf(src);    // 找到src第一次出现的位置
21         int end;
22         while(index != -1) {
23             end = index + src.length();
24             sb.replace(index, end, dst);    // 用dst替换src字符串
25             index = sb.indexOf(src, end);    // 从end开始,可以避免不必要的扫描
26         }
27         // 使用PrintWriter写入文本
28         PrintWriter pw = new PrintWriter("ddd.txt");
29         pw.print(sb.toString());    // 将替换后的文本写回ddd.txt (覆盖写)
30         
31         pw.close();        // 记得关流,不然数据写不进去
32     }
33 }

 

转载于:https://www.cnblogs.com/FengZeng666/p/10840071.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值