public static void main(String[] args) throws IOException {
FileOutputStream fo = new FileOutputStream("D:\\k.txt");
fo.write((int)'好');
fo.close();
        }
我想用java io的字节流向文件存入一个“好”字,结果在文件中出现了乱码,这是为什么?
我发现如果存入一个“a”就可以!
谢谢大家的帮助!

解决方案 »

  1.   

    当你用int的时候,这个汉字已经被拆分了,而且存入文件时没有合并。
      

  2.   

    刚那个看成字符流了。你这个是字符编码的问题。那fo.write()这行换成
    fo.write("好".getBytes("utf-8"));
    就好了。
      

  3.   

    int的问题,去掉应该就可以了
      

  4.   

    建议看一下java.io.OutputStream的public abstract void write(int b)的说明:
    Writes the specified byte to this output stream. The general contract for write is that one byte is written to the output stream. The byte to be written is the eight low-order bits of the argument b. The 24 high-order bits of b are ignored.
    打印一下(int)'好',发现是22909,二进制是101100101111101,而上面红色部分说了,这个方法只会写最低八位,而这个22909用八位显然是不够存储的,所以在这里并没有把这个int数字全部写进去,也就是写进去的数据并不全,当然就出现乱码了。而a转为int后是97,二进制是1100001,用一个字节就能表示完全了,所以能保存完整。
    解决方法,用3楼的应该就OK了。
      

  5.   

    用字符流写
    Writer w = new FileWriter("D:\\k.txt");
    w.write("好")
    w.flush();
    w.close();