好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

解决DataOutputStream乱码的问题

DataOutputStream乱码的问题

这个坑我就先踩为敬了,重要的话说三遍!

千万不要用DataOutputStream的 writeBytes 方法

千万不要用DataOutputStream的 writeBytes 方法

千万不要用DataOutputStream的 writeBytes 方法

我们使用 DataOutputStream 的时候,比如想写入String ,你就会看到三个方法

?

1

2

3

public final void writeBytes(String s)

public final void writeChars(String s)

public final void writeUTF(String str)

OK,那你试着去写入相同的内容后,再去读取一下试试

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

File file = new File( "d:" +File.separator+ "test.txt" );

    DataOutputStream dos = new DataOutputStream( new FileOutputStream(file));

    dos.writeBytes( "你好" );

    dos.writeChars( "你好" );

    dos.writeUTF( "你好" );

    dos.flush();

    dos.close();

   

    DataInputStream dis = new DataInputStream( new FileInputStream(file));

    byte [] b = new byte [ 2 ];

    dis.read(b);

             //  `}

    System.out.println( new String(b, 0 , 2 ));

   

    char [] c = new char [ 2 ];

    for ( int i = 0 ; i < 2 ; i++) {

     c[i] = dis.readChar();

    }

             //你好

    System.out.println( new String(c, 0 , 2 ));

    //你好

    System.out.println(dis.readUTF());

是的,你没看错,writeBytes方法写入的内容读出来,为啥乱码了?

点进去看看实现

?

1

2

3

4

5

6

7

public final void writeBytes(String s) throws IOException {

         int len = s.length();

         for ( int i = 0 ; i < len ; i++) {

             out.write(( byte )s.charAt(i));

         }

         incCount(len);

     }

大哥,这char类型被强转为 byte类型了,失精度了呀,怪不得回不来了,所以使用的时候千万别贪方便,老老实实换成 dos.write("你好".getBytes()); 都好的呀

DataOutputStream写入txt文件数据乱码

这是正常的,如果要读,要用DataInputStream读出,如果仅要保成文本文件直接要FileOutputStream或PrintWriter

?

1

2

3

OutputStreamWriter oStreamWriter = new OutputStreamWriter( new FileOutputStream(file), "utf-8" );

oStreamWriter.append(str);

oStreamWriter.close();

主要是编码方式不一样

要用字符流 而非字节流

BufferedReader类从字符输入流中读取文本并缓冲字符,以便有效地读取字符,数组和行

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

原文链接:https://blog.csdn.net/qq_29914229/article/details/115471851

查看更多关于解决DataOutputStream乱码的问题的详细内容...

  阅读:32次