Unicode编码转中文Java实现
Unicode转中文相关的内容在网上存在很多,本来也不打算重复制造轮子的,但是看了别人的代码,总感觉有点奇怪。比如搜到比较多的一段代码是这样写的:
public static String decodeUnicode(final String dataStr) {
int start = 0;
int end = 0;
final StringBuffer buffer = new StringBuffer();
while (start > -1) {
end = dataStr.indexOf("\\u", start + 2);
String charStr = "";
if (end == -1) {
charStr = dataStr.substring(start + 2, dataStr.length());
} else {
charStr = dataStr.substring(start + 2, end);
}
// 16进制parse整形字符串。
char letter = (char) Integer.parseInt(charStr, 16);
buffer.append(new Character(letter).toString());
start = end;
}
return buffer.toString();
}
仔细分析上述代码,我们会发现这段代码其实只能将纯Unicode编码转为中文,如果其中夹杂了部分英文则在Integer.parseInt(charStr, 16)这段代码处将会抛出异常。当然了,如果是纯粹的Unicode,那就没有问题的。
所以基于此,将该代码进行部分修改:
// 将Unicode转为中文显示
public static String decodeUnicode(final String dataStr) {
int start = 0;
int end = 0;
int size = dataStr.length();
final StringBuilder buffer = new StringBuilder();
// 找到第一个\\u的位置
while (start < size) {
end = dataStr.indexOf("\\u", start);
end = end < 0 ? size : end;
String charStr;
if (end == start) {
// 如果start == end,则表示从start开始就是Unicode编码,
start += 2;
end += 6;
charStr = dataStr.substring(start, end);
// 16进制parse整形字符串。
char letter = (char) Integer.parseInt(charStr, 16);
buffer.append(letter);
} else {
// 如果start != end,则表示从start到end-1处都没有Unicode编码
buffer.append(dataStr, start, end - 1);
}
// 重新调整start的位置
start = end;
}
return buffer.toString();
}
// 读取文件filePath中的内容并将其中的Unicode转为中文后保存在文件targetFilePath中
public static void decodeUnicodeToFile(String filePath, String targetFilePath) {
if (filePath == null || targetFilePath == null) {
System.err.println("path不能为空!");
}
try {
File file = new File(filePath);
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] bytes = bis.readAllBytes();
StringBuilder strByte = new StringBuilder();
for (byte b : bytes) {
strByte.append((char)b);
}
String str = decodeUnicode(strByte.toString());
File file2 = new File(targetFilePath);
bytes = str.getBytes();
bos.writeBytes(bytes);
bos.writeTo(new FileOutputStream(file2));
bos.close();
bis.close();
} catch (Exception e){
System.out.println("exec error: " + e.getMessage());
}
}
本文探讨了Unicode编码转中文的Java实现,指出常见代码的局限性,即只能处理纯编码而无法处理混合英文的情况,并提供了经过修改的代码来解决这个问题。

2855

被折叠的 条评论
为什么被折叠?



