筆者的場景是這樣的,筆者使用code smith作為代碼生成工具,并在Eclipse中做插件開發(fā),code smith天生
對GB的支持比較弱,只能生成UTF-8編碼,這在Eclipse開發(fā)的過程中不會存在問題,但是在使用Eclipse的導(dǎo)出
功能時(shí),Eclipse底層使用ANT的執(zhí)行方式,ANT的默認(rèn)字符集默認(rèn)使用當(dāng)前系統(tǒng)的字符集,這時(shí)在編譯導(dǎo)出的時(shí)候,
會出現(xiàn)字符無法識別的問題,導(dǎo)致導(dǎo)出或者打包失敗。
一種方式可以改變Eclipse工程的默認(rèn)字符集,以及自動生成的ant配置文件中字符集的配置,這對于單個(gè)工程是有
效的,但處理工程間依賴時(shí),被依賴的工程同樣會出現(xiàn)字符集問題,即使被依賴工程設(shè)定ant的字符集。
另一種方式,是手工轉(zhuǎn)換,講UTF-8的字符集轉(zhuǎn)換為GBK的,微軟的網(wǎng)站提供了一個(gè)批量轉(zhuǎn)換工具,但是在轉(zhuǎn)換之后,
文檔的最前面還會有可能存在多于字符,并導(dǎo)致ant打包失敗
最后,沒辦法自己寫了一個(gè)字符集轉(zhuǎn)換工具,因?yàn)槭亲约河?,所以夠用就行,下面是轉(zhuǎn)換部分的代碼,實(shí)現(xiàn)UTF8到
GBK的轉(zhuǎn)換,其他轉(zhuǎn)換可以對代碼稍作修改。
import org.apache.commons.lang.ArrayUtils;
public class EncodeRepairTool {
public static final byte[] bPre = "EFBBBF".getBytes();
private int i = 0;
/**
* @param args
*/
public static void main(String[] args) {
String path = "D:\\eclipse-dev-3.3\\workspace";
File file = new File(path);
EncodeRepairTool scanner = new EncodeRepairTool();
scanner.scanFolder(file);
}
public void scanFolder(File file) {
if (file.isDirectory()) {
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
scanFolder(files[i]);
}
} else if (file.getName().endsWith(".java")) {
removePreCode(file);
}
}
private void removePreCode(File file) {
try {
FileInputStream fis = new FileInputStream(file);
int size = fis.available();
if (size < 24) {
return;
}
i ++ ;
byte[] bs = new byte[size];
fis.read(bs);
byte[] tbs = ArrayUtils.subarray(bs, 0, 3);
byte[] tbs1 = new byte[] { new Integer(0xEF).byteValue(),
new Integer(0xBB).byteValue(),
new Integer(0xBF).byteValue() };
boolean bol = false;
if (tbs[0] == tbs1[0] && tbs[1] == tbs1[1] && tbs[2] == tbs1[2]) {
bol = true;
}
fis.close();
if (!bol) {
System.out.println(" " + i + " : " + file.getName());
tbs = bs;
}
else {
System.out.println("**" + i + " : " + file.getName());
tbs = ArrayUtils.subarray(bs, 3, size);
}
InputStreamReader reader = new InputStreamReader(new ByteArrayInputStream(tbs), "UTF-8");
BufferedReader br = new BufferedReader(reader);
StringBuffer buffer = new StringBuffer();
String s = br.readLine();
while (s != null) {
buffer.append(s);
buffer.append("\n");
s = br.readLine();
}
reader.close();
byte[] nbs = buffer.toString().getBytes("GBK");
FileOutputStream fos = new FileOutputStream(file);
fos.write(nbs);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
// TODO 自動生成 catch 塊
e.printStackTrace();
} catch (IOException e) {
// TODO 自動生成 catch 塊
e.printStackTrace();
}
}
}