Solution to garbled dataoutputstream: 1. Write String through "dos.write("...".getBytes());"; 2. Set "new OutputStreamWriter(new FileOutputStream(file), "utf-8");" is enough.
#The operating environment of this tutorial: Windows 10 system, Java version 8.0, Dell G3 computer.
What should I do if the dataoutputstream is garbled?
Solve the problem of DataOutputStream garbled characters
I will step on this trap first, and say the important things three times!
Never use the writeBytes method of DataOutputStream
Never use the writeBytes method of DataOutputStream
千Never use the writeBytes method of DataOutputStream
When we use DataOutputStream, for example, if we want to write String, you will see three methods
public final void writeBytes(String s) public final void writeChars(String s) public final void writeUTF(String str)
OK , then you try to write the same content and then read it again
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());
Yes, you read it right, the content written by the writeBytes method is read out, Why is it garbled?
Click in to see the implementation
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); }
Brother, this char type has been forcibly converted to byte type, and the accuracy has been lost. No wonder it cannot be returned, so use Don't be greedy for convenience, just replace it with dos.write("Hello".getBytes()); It's all good
This is normal. If you want to read, use DataInputStream to read. If you only want to save it as a text file, directly use FileOutputStream or PrintWriter
OutputStreamWriter oStreamWriter = new OutputStreamWriter(new FileOutputStream(file), "utf-8"); oStreamWriter.append(str); oStreamWriter.close();
The main reason is that the encoding method is different
Use a character stream instead of a byte stream
The BufferedReader class reads text from a character input stream and buffers the characters to effectively read characters, arrays and lines
Recommended learning: "Java Video Tutorial"
The above is the detailed content of What to do if the dataoutputstream is garbled?. For more information, please follow other related articles on the PHP Chinese website!