博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
替换文件夹中特定字符串工具类
阅读量:7071 次
发布时间:2019-06-28

本文共 1696 字,大约阅读时间需要 5 分钟。

hot3.png

这里与大家分享一个替换文件中某字符串的小程序,经测试完全可用,希望对大家有帮助

import java.io.BufferedReader;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

public class ReplaceWordUtil {

 public static void main(String[] args) {
  /**
   * arg0 文件路径
   * arg1 需要替换的内容
   * arg2 新内容
   */
  iteratorDirectory("d:/test","","");
 }

 public static void iteratorDirectory(String filepath,String oldStr,String replaceStr) {

  File file = new File(filepath);
  if (file.isDirectory()) {
   String[] fileList =  file.list();
   
   for(int i=0;i<fileList.length;i++) {
    iteratorDirectory(filepath+"\\"+fileList[i],oldStr,replaceStr);
   }
  }else {
   replaceTxtByStr(filepath,oldStr,replaceStr);
  }
 }
  public static void replaceTxtByStr(String path,String oldStr,String replaceStr) {
         String temp = "";
         int len = oldStr.length();
         StringBuffer tempBuf = new StringBuffer();
         try {
             File file = new File(path);
             FileInputStream fis = new FileInputStream(file);
             InputStreamReader isr = new InputStreamReader(fis);
             BufferedReader br = new BufferedReader(isr);
             StringBuffer buf = new StringBuffer();
           
             while((temp = br.readLine()) != null) {
              if(temp.contains(oldStr)) {
               int index = temp.indexOf(oldStr);
               tempBuf.append(temp);
               tempBuf.replace(index, index+len, replaceStr);
               buf.append(tempBuf);
               tempBuf.setLength(0);
              }else {
               buf.append(temp);
              }
               buf = buf.append(System.getProperty("line.separator"));
              
             }
             br.close();
             FileOutputStream fos = new FileOutputStream(file);
             PrintWriter pw = new PrintWriter(fos);
             pw.write(buf.toString().toCharArray());
             pw.flush();
             pw.close();
         } catch (IOException e) {
             e.printStackTrace();
         }
     }

}

转载于:https://my.oschina.net/u/551903/blog/163096

你可能感兴趣的文章
多种替身邮方法总结!
查看>>
沟通比文档更有力
查看>>
在页面头部<!DOCTYPE html ....> 前面不能有任何输出
查看>>
hdu 2102 A计划(双层BFS)(具体解释)
查看>>
大型机器学习
查看>>
FluentNhibernate 不支持存储过程
查看>>
Python 修改电脑DNS
查看>>
复杂 Listview 显示 多个样式
查看>>
[Unity3D]Unity3D游戏开发之角色控制漫谈
查看>>
git branch merge到master
查看>>
EJB--事务管理 .
查看>>
在vmware里面免费安装纯净的xp虚拟机
查看>>
什么是RESTfull?理解RESTfull架构【转】
查看>>
linux lsof命令详解
查看>>
MySQL中concat函数
查看>>
代理模式
查看>>
Linux命令 cat命令
查看>>
poj1007 逆序数 排序
查看>>
周末轻松话卷积(上)
查看>>
【转】对C# 中堆栈,堆,值类型,引用类型的理解
查看>>