今天同事在保存文件时,需要保存一个“元”字,这个文件有且只有一个汉字,发生了乱码。工程是UTF-8编码,文件格式要求是GBK。

于是就多做了几种测试,发现很有意思:

  1. 当有且只有一个“元”字时(其他字符或是数字,或是字母,下同),肯定会发生乱码。
  2. 当不是“元”,而是其他汉字时(非yuan这种发音),都不会发生乱码。
  3. 当所有都是“元”字时,也会发生乱码。

此问题尚未搞明白!

package net.bwda.Test;

import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;

public class StringTest {

    public static void main(String[] args) {
        String strTest1 = "元";
        String strTest2 = "和";
        String strTest3 = "元元元元元";
        String strTest4 = "缘";
        try {
            stringToFile(strTest1, "d:\\1.txt", "GBK");
            stringToFile(strTest2, "d:\\2.txt", "GBK");
            stringToFile(strTest3, "d:\\3.txt", "GBK");
            stringToFile(strTest4, "d:\\4.txt", "GBK");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public final static boolean stringToFile(String strContent, String strFilePath, String strCoding) {
        boolean blnResult = false;
        FileOutputStream fileOutputStream = null; // 文件输出对象
        Writer writer = null;
        try {
            fileOutputStream = new FileOutputStream(strFilePath);
            if (strCoding == null || strCoding.trim().length() <= 0) {
                writer = new OutputStreamWriter(fileOutputStream);
            } else {
                writer = new OutputStreamWriter(fileOutputStream, strCoding);
            }
            writer.write(strContent);
            writer.flush();
            writer.close();
            fileOutputStream.close();
            blnResult = true;
        } catch (Exception e) {
        } finally {
            writer = null;
            fileOutputStream = null;
        }
        return blnResult;
    }
}
View Code

相关文章:

  • 2021-11-10
  • 2022-12-23
  • 2021-11-13
  • 2021-12-26
  • 2021-09-19
  • 2021-08-16
猜你喜欢
  • 2022-12-23
  • 2021-12-05
  • 2022-02-25
  • 2022-12-23
  • 2022-12-23
  • 2021-12-23
  • 2022-12-23
相关资源
相似解决方案