java字符串替换replace成功却得不到结果

 

今天刚需要用到java的字符串的替换, 本来觉得挺简单的问题,却总也解决不了。用indexOf()明明也找到了字符串中含有需要替换的字符串,字符串明明也是替换了,却总也输出不了正确结果。


 public static void replace(){
     String path="D:\\zz2\\";
     String filepath="D:\\zz3\\";
     File folder=new File(path);
     File[] folderList=folder.listFiles();
     for(int i=0;i<folderList.length;i++){
     File[] fileList=folderList[i].listFiles();
     try {
BufferedReader reader=new BufferedReader(new FileReader(fileList[i]));

String filePath=filepath+fileList[i].getName();
File file=new File(filePath);
if(!file.exists()){
file.createNewFile();
}
FileWriter writer=new FileWriter(filepath+fileList[i].getName(),true);

String temp=null;
                while((temp=reader.readLine())!=null){
                 temp="<td class=\"nocontentTd\"<";
                 System.out.println(temp.indexOf("<td class=\"nocontentTd\"<"));
                 temp.replace("<td class=\"nocontentTd\"<", "<td class=\"nocontentTd\"><");
                 writer.write(temp+"\n");
                 System.out.println(temp);
                }

                reader.close();
                writer.close();

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
    
     }
    }

发现temp还是没变,后来发现relpace是有返回值的,于是

while((temp=reader.readLine())!=null){
                 temp="<td class=\"nocontentTd\"<";
                 System.out.println(temp.indexOf("<td class=\"nocontentTd\"<"));
                 temp=temp.replace("<td class=\"nocontentTd\"<", "<td class=\"nocontentTd\"><");
                 writer.write(temp+"\n");
                 System.out.println(temp);
                }

就得到了正确结果。

我们来看String的replaceAll()方法的实现:

  
  
   public String replaceAll(String regex, String replacement) {    return Pattern.compile(regex).matcher( this ).replaceAll(replacement);   }


    我们可以看到,其最终是调用了matcher(this).replaceAll(replacement)方法来实现的,我们看其是怎么实现的:

  
  
   public String replaceAll(String replacement) {   reset();   boolean result = find();    if (result) {   StringBuffer sb = new StringBuffer();    do {   appendReplacement(sb, replacement);   result = find();   } while (result);   appendTail(sb);    return sb.toString();   }    return text.toString();   }

可见最终是把temp的值传进去,temp本身没变,最终的返回结果才是要的结果。



  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值