从光盘上拷下来的一些源码,源文件是ansi的,放到eclipse的utf8的项目里后中文全是乱码,于是顺手写了个gbk转utf8的小程序。
//输入File类型的目录或文件,转换里边所有文件
public static void gbk2utf(File file) {
if (file.isDirectory()) {
// 目录
File subDictories[] = file.listFiles();
for (int i = 0; i < subDictories.length; i++) {
gbk2utf(subDictories[i]);
}
} else {
// 文件
String filePath = file.getPath();
if (filePath.lastIndexOf(".") != -1) {
String tmpFilePath = filePath.substring(0, filePath .lastIndexOf("."))+ "_utftmp"
+ filePath.substring(filePath.lastIndexOf("."));
try {
FileInputStream fin = new FileInputStream(file);
BufferedReader bfReader = new BufferedReader(new InputStreamReader(fin, "GBK"));
FileOutputStream fout = new FileOutputStream(tmpFilePath);
BufferedWriter bfWriter = new BufferedWriter(new OutputStreamWriter(fout, "utf-8"));
String str;
while ((str = bfReader.readLine()) != null) {
bfWriter.write(str);
bfWriter.newLine();
}
bfReader.close();
fin.close();
bfWriter.close();
fout.close();
// 删除旧文件
file.delete();
// 重命名新文件
File newFile = new File(tmpFilePath);
newFile.renameTo(new File(filePath));
} catch (Exception e) {
e.printStackTrace();
}
}
}
}