从网上下载的项目,有时候.java文件的编码是ANSI。导入到自己的MyEclipse后,查看项目源码的时候,总是乱码。
一个个.java去修改的话, 既麻烦又不现实。所以写了下面这个工具类,进行批量转编码。
代码的原理仅仅就是遍历文件,然后使用流,对按照文件的原编码进行读取,用目的编码进行写操作。
直接上源码:
package test;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;public class Main { // private String sDirectory = "D:/Workspaces/BeyondDiscuz/src/com"; private String sDirectory = "D:\\Workspaces\\BeyondDiscuz\\src\\com"; private String dDirectory = "D:\\Workspaces\\BeyondDiscuz\\src\\cn"; public static void main(String[] args) { Main 吗 = new Main(); try { 吗.readerFile(吗.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")); // BufferedReader r = new BufferedReader(new InputStreamReader(new FileInputStream(c))); File newF = new File(newFile); newF.createNewFile(); // BufferedWriter w = new BufferedWriter(new // OutputStreamWriter(new FileOutputStream(newF), "UTF-8")); BufferedWriter w = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(newF))); // BufferedWriter w = new BufferedWriter(new FileWriter(newFile)); String lineText = null; while ((lineText = r.readLine()) != null) { // String temp = new String(lineText.getBytes("ISO-8859-1"), "UTF-8"); w.write(lineText); w.newLine(); } w.close(); r.close(); } else { readerFile(child[i]); } } } }}
上面自己的写代码只是基本思路,下面是更简洁的代码:
public static void main(String[] args) { try { String srcDirPath = "E:\\eclipseWorkspaceSandbase\\test"; // 转为UTF-8编码格式源码路径 String utf8DirPath = "E:\\eclipseWorkspaceSandbase\\test-8"; // 获取所有java文件 CollectionjavaGbkFileCol = FileUtils.listFiles(new File(srcDirPath), new String[] { "java" }, true); for (File javaGbkFile : javaGbkFileCol) { System.out.println(javaGbkFile); // UTF8格式文件路径 String utf8FilePath = utf8DirPath + javaGbkFile.getAbsolutePath().substring(srcDirPath.length()); // 使用GBK读取数据,然后用UTF-8写入数据 FileUtils.writeLines(new File(utf8FilePath), "UTF-8", FileUtils.readLines(javaGbkFile, "GBK")); } } catch (Exception e) { e.printStackTrace(); } }