有些文件中存在Unicode字符和非Unicode字符,如何利用java快速的把文件中的Unicode字符转换为汉字而不影响文件中的其他字符呢,
我们知道虽然java 在控制台会把Unicode字符直接输出成汉字,但是当遇到文件中的Unicode和非Unicode字符在一起的时候却不好用了。
下面是代码,只需要把代码中的路径替换为你想要的路径,在建立一个转换后的文件路径。其他代码无需改变。
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader; public class Zhtest { public static void main(String[] args) throws IOException {
//源文件路径
String path = "d:\\Blaze.txt";
//输出文件路径
File write = new File("d:\\Blaze1.txt"); File file = null;
BufferedReader br = null;
BufferedWriter bw = new BufferedWriter(new FileWriter(write));
file = new File(path);
br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "gbk"));
StringBuilder sb = new StringBuilder();
String length = "";
while ((length = br.readLine()) != null) {
sb.append(length);
bw.write(ascii2Native(sb.toString()) + "\r\n");
bw.flush();
sb = new StringBuilder();
} } public static String ascii2Native(String str) {
StringBuilder sb = new StringBuilder();
int begin = 0;
int index = str.indexOf("\\u");
while (index != -1) {
sb.append(str.substring(begin, index));
sb.append(ascii2Char(str.substring(index, index + 6)));
begin = index + 6;
index = str.indexOf("\\u", begin);
}
sb.append(str.substring(begin));
return sb.toString();
} private static char ascii2Char(String str) {
if (str.length() != 6) {
throw new IllegalArgumentException("长度不足6位");
}
if (!"\\u".equals(str.substring(0, 2))) {
throw new IllegalArgumentException("字符必须以 \"\\u\"开头.");
}
String tmp = str.substring(2, 4);
int code = Integer.parseInt(tmp, 16) << 8;
tmp = str.substring(4, 6);
code += Integer.parseInt(tmp, 16);
return (char) code;
} }