项目中需要生成一个GBK文件,文件中只有一个汉字“元”,其余都是字母或数字。发现这个字出现了乱码,经测试,只有strTest2不是乱码,其余均是乱码。貌似和发音还有点关系,请问如何才能正确输出一个“元”字?已经在网上试过了好多方法,例如utf-8转unicode,再转GBK,还有new String(strTest1.getBytes("GBK"),"GBK")等等。本工程是utf-8编码。 1 public class StringTest {
2
3 public static void main(String[] args) {
4 String strTest1 = "元";
5 String strTest2 = "和";
6 String strTest3 = "元元元元元";
7 String strTest4 = "缘";
8 try {
9 stringToFile(strTest1, "d:\\1.txt", "GBK");
10 stringToFile(strTest2, "d:\\2.txt", "GBK");
11 stringToFile(strTest3, "d:\\3.txt", "GBK");
12 stringToFile(strTest4, "d:\\4.txt", "GBK");
13 } catch (Exception e) {
14 // TODO Auto-generated catch block
15 e.printStackTrace();
16 }
17 }
18
19 public final static boolean stringToFile(String strContent, String strFilePath, String strCoding) {
20 boolean blnResult = false;
21 FileOutputStream fileOutputStream = null; // 文件输出对象
22 Writer writer = null;
23 try {
24 fileOutputStream = new FileOutputStream(strFilePath);
25 if (strCoding == null || strCoding.trim().length() <= 0) {
26 writer = new OutputStreamWriter(fileOutputStream);
27 } else {
28 writer = new OutputStreamWriter(fileOutputStream, strCoding);
29 }
30 writer.write(strContent);
31 writer.flush();
32 writer.close();
33 fileOutputStream.close();
34 blnResult = true;
35 } catch (Exception e) {
36 } finally {
37 writer = null;
38 fileOutputStream = null;
39 }
40 return blnResult;
41 }
42 }
添加回答
举报
0/150
提交
取消