替換文件夾中特定字符串工具類

這裏與你們分享一個替換文件中某字符串的小程序,經測試徹底可用,但願對你們有幫助 java

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","","");
 } app

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

} 字符串

相關文章
相關標籤/搜索