代码如下
/**
* 将Unicode文件转换成GBK文件
* @param filePath Unicode文件路径
* @param savePath GBK文件保存路径
*/
public static void unicodeFile2GBKFile(String filePath,String savePath){
// 将unicode文件转换成String类型
String str = fileToString(filePath);
// 将unicode字符串转换成GBK字符串
str = unicodeToGBK(str);
// 将GBK字符串写入savePath路径的文件
try ( FileOutputStream fos = new FileOutputStream(savePath)){
fos.write(str.getBytes("GBK"));
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 将Unicode字符串转换成GBK字符串
* @param unicodeStr Unicode字符串
* @return GBK字符串
*/
private static String unicodeToGBK(String unicodeStr){
int index = 0;
StringBuilder builder = new StringBuilder();
int unicodeLength = unicodeStr.length();
while(index<unicodeLength){
if(index >= unicodeLength-1 || !"\\u".equals(unicodeStr.substring(index,index+2))){
builder.append(unicodeStr.charAt(index));
index++;
}
}
return builder.toString();
}
/**
* 将unicode文件转换成String类型
* @param filePath unicode文件路径
* @return Unicode字符串
*/
private static String fileToString(String filePath){
StringBuilder builder = new StringBuilder();
try (BufferedReader br = new BufferedReader(
new InputStreamReader(
new FileInputStream(filePath),"Unicode"))){
String str = null;
char[] chars = new char[1024*10];
int len = -1;
while ((len = br.read(chars,0,len))!= -1){
str = new String(chars,0,len);
builder.append(str);
}
} catch (IOException e) {
e.printStackTrace();
}
return builder.toString();
}