题意:
将文本文件中的所有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 }