經常有些檔案中的一些內容需要批量替換,手動的用編輯器替換,只能針對單個檔案,涉及多檔案的時候,很費時間。下面小編準備了關於Java文字檔案批量替換小程式的方法,提供給大家參考!
由於有個web專案的字符集編碼原本使用gb2312,現在想改為utf-8編碼,專案下有很多的html,手動去修改相當麻煩,比較懶,於是就寫了如下的java程式對html檔案中的charset=gb2312進行替換,替換為 charset=utf-8。(注:Dreamweaver 可以批量替換)
程式碼如下:
import eredReader;
import eredWriter;
import ;
import Filter;
import InputStream;
import OutputStream;
import ception;
import tStreamReader;
import utStreamWriter;
import tWriter;
import pportedEncodingException;
public class ContextReplace {
private static String srcStr = "charset=gb2312";
private static String desStr = "charset=utf-8";
private static String srcDir = "f:test";
private static FileFilter filter = new FileFilter() {
public boolean accept(File pathname) {
// 只處理:目錄 或是 檔案
if (rectory()
|| (le() && ame()With(
""))) {
return true;
} else {
return false;
}
}
};
public static void readDir(File file) {
// 以過濾器作為引數
File[] files = Files(filter);
for (File subFile : files) {
// 處理目錄
if (rectory()) {
readDir(subFile);
}
// 處理檔案
else {
tln(" 原始檔:t" + bsolutePath());
tln("---------------------------");
try {
replace(bsolutePath(), srcStr, desStr);
} catch (UnsupportedEncodingException e) {
tStackTrace();
} catch (IOException e) {
tStackTrace();
}
}
}
}
public static void replace(String infilename, String from, String to)
throws IOException, UnsupportedEncodingException {
File infile = new File(infilename);
BufferedReader in = new BufferedReader(new InputStreamReader(
new FileInputStream(infile), "utf-8"));
File outfile = new File(infile + "");
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(outfile), "utf-8")));
String reading;
while ((reading = Line()) != null) {
tln(aceAll(from, to));
}
e();
e();
te();
meTo(infile);
}
public static void main(String[] args) {
File srcFile = new File(srcDir);
readDir(srcFile);
srcFile = null;
}
}