Created
October 17, 2012 01:22
-
-
Save turbidsoul/3903208 to your computer and use it in GitHub Desktop.
转换指定目录及其子目录下所有文件的编码从GBK到UTF-8
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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