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