html批量转换UTF-8

import java.io.*;
//---------------------------------
// 文件过滤器
class HTMLFilter implements FilenameFilter {
public boolean accept(File directory, String name) {
if (name.endsWith(".html")) return true;
if (name.endsWith(".htm")) return true;
if (name.endsWith(".HTML")) return true;
if (name.endsWith(".HTM")) return true;
return false;
}
}

class BatchEncoder {
String oldFile = null;
public BatchEncoder(String oldFile) {
this.oldFile = oldFile;
File f = new File(oldFile);
tree(f);
}

public void tree(File f) {
File[] childs = f.listFiles(new HTMLFilter());
if (childs == null) {
return;
}
for (int i = 0; i < childs.length; i++) {
if (childs[i].isDirectory()) {
tree(childs[i]);
} else if (childs[i].isFile()) {
parse(childs[i]);
}
}

}

public void parse(File f) {
BufferedReader br = null;
BufferedWriter bw = null;
String UTF = "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />";
String s = "";
try {
InputStreamReader isr = new InputStreamReader(
new FileInputStream(f));
OutputStreamWriter osw = new OutputStreamWriter(
new FileOutputStream("D:\\BatchEncoder_bak\\" + f.getName()),
"UTF-8");
br = new BufferedReader(isr);
bw = new BufferedWriter(osw);
if (!(isr.getEncoding().equals("UTF8"))) {
while ((s = br.readLine()) != null) {
if (!(s.matches("<meta.*charset=UTF-8.*>$"))) {
s = s.replaceAll("<meta.*>$", UTF);
}
bw.write(s);
bw.newLine();

}
bw.flush();
testEncoding(f, osw);

}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}

}

public void testEncoding(File f, OutputStreamWriter osw) {
if(f.isFile()) {
if (osw.getEncoding().equals("UTF8")) {
System.out.println(f.getName()
+ " --> Encoding resounding success! current Encoding is: "
+ osw.getEncoding());
} else {
System.out.println(f.getName()
+ " --> Encoding failure! current Encoding is:"
+ osw.getEncoding());
}
}

}
}

// ------------------------------------------------------------
// Main Method
public class TestBatchEncoder {
public static void main(String[] args) {
BatchEncoder be = new BatchEncoder("D:\\BatchEncoder");
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值