zoukankan      html  css  js  c++  java
  • 替换文本:将文本文件中的所有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() + "
    ";    // 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('
    ');
    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 }
  • 相关阅读:
    一分钟认识:Cucumber框架(一)
    迭代=冲刺?
    Nresource服务之接口缓存化
    58集团支付网关设计
    服务治理在资源中心的实践
    资源中心——连接池调优
    4种常用的演讲结构: 黄金圈法则结构、PREP结构、时间轴结构、金字塔结构
    微服务时代,领域驱动设计在携程国际火车票的实践
    Sentinel -- FLOW SLOT核心原理篇
    管理篇-如何跨部门沟通?
  • 原文地址:https://www.cnblogs.com/FengZeng666/p/10840071.html
Copyright © 2011-2022 走看看