今天在做项目中,需要用到一些CSS和JS文件,于是将之前项目中的文件拷贝过来,项目运行时发现出现乱码,于是便开始修改,结果改的时候发现四五十个文件,这不得改半天!索性自己写了个工具类,批量修改字符编码,几秒钟完事,分享给大家,以后再也不用单独修改编码了。
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
/**
* 字符编码转化工具类
* 可以批量对文件编码格式进行转化 支持同时修改多个文件夹中的文件
* auther: wugongzi
* date: 2020-8-21
*/
public class ConvertEncode {
//源文件路径
private String sDirectory = "E:\Work\css";
//目标文件路径
private String dDirectory = "E:\Work\css1";
public static void main(String[] args) {
ConvertEncode encode = new ConvertEncode();
try {
encode.readerFile(encode.sDirectory);
} catch (IOException e) {
e.printStackTrace();
}
}
public void readerFile(String filePath) throws IOException {
if ("".equals(filePath) || null == filePath) {
return;
}
File f = new File(filePath);
if (f.isDirectory()) {
String[] child = f.list();
for (int i = 0; i < child.length; i++) {
String path = f.getAbsolutePath() + File.separator;
String newPath = path.replace(this.sDirectory, this.dDirectory);
child[i] = path + child[i];
File c = new File(child[i]);
String newFile = child[i].replace(this.sDirectory, this.dDirectory);
System.out.println("旧路径:" + path);
System.out.println("新路径:" + newPath);
File newP = new File(newPath);
if (!newP.exists())
newP.mkdir();
if (c.isFile()) {
System.out.println("旧文件:" + child[i]);
System.out.println("新文件:" + newFile);
//源文件编码格式 支持以下格式Charset US-ASCII ISO-8859-1 UTF-8 UTF-16BE UTF-16LE UTF-16
BufferedReader r = new BufferedReader(new InputStreamReader(new FileInputStream(c), "GBK"));
File newF = new File(newFile);
newF.createNewFile();
// 目标文件编码格式
BufferedWriter w = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(newF), "UTF-8"));
String lineText = null;
while ((lineText = r.readLine()) != null) {
w.write(lineText);
w.newLine();
}
w.close();
r.close();
} else {
readerFile(child[i]);
}
}
}
}
}