经常有些文件中的一些内容需要批量替换,手动的用编辑器替换,只能针对单个文件,涉及多文件的时候,很费时间。下面小编准备了关于Java文本文件批量替换小程序的方法,提供给大家参考!
由于有个web项目的字符集编码原本使用gb2312,现在想改为utf-8编码,项目下有很多的html,手动去修改相当麻烦,比较懒,于是就写了如下的java程序对html文件中的charset=gb2312进行替换,替换为 charset=utf-8。(注:Dreamweaver 可以批量替换)
代码如下:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
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) {
// 只处理:目录 或是 .html文件
if (pathname.isDirectory()
|| (pathname.isFile() && pathname.getName().endsWith(
".html"))) {
return true;
} else {
return false;
}
}
};
public static void readDir(File file) {
// 以过滤器作为参数
File[] files = file.listFiles(filter);
for (File subFile : files) {
// 处理目录
if (subFile.isDirectory()) {
readDir(subFile);
}
// 处理文件
else {
System.err.println(" 源文件:\t" + subFile.getAbsolutePath());
System.err.println("---------------------------");
try {
replace(subFile.getAbsolutePath(), srcStr, desStr);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
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 + ".tmp");
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(outfile), "utf-8")));
String reading;
while ((reading = in.readLine()) != null) {
out.println(reading.replaceAll(from, to));
}
out.close();
in.close();
infile.delete();
outfile.renameTo(infile);
}
public static void main(String[] args) {
File srcFile = new File(srcDir);
readDir(srcFile);
srcFile = null;
}
}