Skip to content

Instantly share code, notes, and snippets.

@turbidsoul
Created October 17, 2012 01:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save turbidsoul/3903208 to your computer and use it in GitHub Desktop.
Save turbidsoul/3903208 to your computer and use it in GitHub Desktop.
转换指定目录及其子目录下所有文件的编码从GBK到UTF-8
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
/**
*
*/
/**
* @author <p>Innate Solitary 于2012-5-3 9:16:45</p>
*
*/
public class UnicodeCover {
/**
* @param args
*/
public static void main(String[] args) throws Exception {
long start = System.currentTimeMillis();
unCoverUnicodeForDir("F:\\work\\jwzt\\source\\soms4", "F:\\work\\jwzt\\test", "F:\\work\\jwzt\\source\\soms4\\", "GBK");
long end = System.currentTimeMillis();
System.out.println(end - start);
}
public static void unCoverUnicodeForDir(String dirPath, String outpath, String prefixPath, String sourceCharset) throws Exception {
File dir = new File(dirPath);
if(!dir.isDirectory()) {
String content = unCoverUnicode(dirPath, sourceCharset);
File file = new File(outpath + "/" + dirPath.replace(prefixPath, "").replace(dirPath.split("\\\\")[dirPath.split("\\\\").length - 1], ""));
if(!file.exists()) {
file.mkdirs();
}
FileOutputStream fos= new FileOutputStream(outpath + "/" + dirPath.replace("F:\\work\\jwzt\\source\\soms4\\", ""));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
bw.write(content);
bw.close();
fos.close();
return;
}
File[] files = dir.listFiles();
for (File file : files) {
System.out.println(file.getAbsolutePath());
unCoverUnicodeForDir(file.getAbsolutePath(), outpath, prefixPath, sourceCharset);
}
}
public static String unCoverUnicode(String filePath, String sourceCharset) throws Exception {
String cmd = "native2ascii -reverse " + filePath;
BufferedReader br = new BufferedReader(new InputStreamReader(Runtime.getRuntime().exec(cmd).getInputStream(), sourceCharset));
StringBuffer sb = new StringBuffer();
for(String line = br.readLine(); line != null; line = br.readLine()) {
sb.append(line).append("\r\n");
}
br.close();
return sb.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment