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

来源:互联网 发布:淘宝店铺素材免费下载 编辑:程序博客网 时间:2024/05/18 02:05

 

今天刚需要用到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本身没变,最终的返回结果才是要的结果。



原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 win10鼠标不反应怎么办 快把游戏打不开怎么办 消防退出现役士兵怎么办 武警退出现役士兵怎么办 c盘空间不够怎么办 解压文件被破坏怎么办 exe被拒绝访问怎么办 游戏文件删除了怎么办? 战地一打不开怎么办 迅雷怎么下载不动怎么办 电脑带不动游戏怎么办 sap wm自动上架怎么办 战地1停止运行怎么办 c9pro检测到潮湿怎么办 战地1卡顿怎么办 战地1停止工作怎么办 大写锁定shift解除怎么办 游戏突然掉帧怎么办 oppo应用商店打不开怎么办 ps4战地1校园网怎么办 战地4延迟高怎么办 红米手机打不开怎么办 台式电脑网页打不开怎么办 电脑网页很多都打不开怎么办 qq发送不了位置怎么办 qq无法找到入口怎么办 玩游戏总是掉怎么办 ipad所有按键失灵怎么办 手机启动器停止运行怎么办 安卓版泰拉瑞亚联机失去连接怎么办 吃鸡安装不了怎么办 obb文件丢失了怎么办 dnf登录闪退怎么办 泰拉瑞亚地图找不到备份怎么办 服务器没远程管理卡怎么办 tplink上不了网怎么办 键盘端口坏了怎么办 小米路由dns错误怎么办 电脑内存性能低怎么办 nas硬盘坏了怎么办 360安装环境异常怎么办