现在的位置: 首页 > 综合 > 正文

一个替换某文件夹下的所有文件中特定字符串的小工具

2013年12月01日 ⁄ 综合 ⁄ 共 1909字 ⁄ 字号 评论关闭

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

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();
         }
     }

}

抱歉!评论已关闭.