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

题意:

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

 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 }

猜你喜欢

转载自www.cnblogs.com/FengZeng666/p/10840071.html