utf到GBK转码

/*使用code smith作为代码生成工具,并在Eclipse中做插件开发,code smith天生对GB的支持比较弱,只能生成UTF-8编码,这在Eclipse开发的过程中不会存在问题,但是在使用Eclipse的导出功能时,Eclipse底层使用ANT的执行方式,ANT的默认字符集默认使用当前系统的字符集,这时在编译导出的时候,会出现字符无法识别的问题,导致导出或者打包失败。

一种方式可以改变Eclipse工程的默认字符集,以及自动生成的ant配置文件中字符集的配置,这对于单个工程是有效的,但处理工程间依赖时,被依赖的工程同样会出现字符集问题,即使被依赖工程设定ant的字符集。

另一种方式,是手工转换,讲UTF-8的字符集转换为GBK的,微软的网站提供了一个批量转换工具,但是在转换之后,文档的最前面还会有可能存在多于字符,并导致ant打包失败最后,没办法自己写了一个字符集转换工具,因为是自己用,所以够用就行,下面是转换部分的代码,实现UTF8到

GBK的转换,其他转换可以对代码稍作修改。*/

 

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(); 

}

 

}

 

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值