Solve the problem of DataOutputStream garbled code
- 2021-11-14 06:01:14
- OfStack
The Problem of DataOutputStream Garbled Code
I'll step on this pit for respect first, and say 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 try to read 1
File file = new File("d:"+File.separator+"test.txt");
DataOutputStream dos = new DataOutputStream(new FileOutputStream(file));
dos.writeBytes(" How do you do ");
dos.writeChars(" How do you do ");
dos.writeUTF(" How do you do ");
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();
}
// How do you do
System.out.println(new String(c, 0, 2));
// How do you do
System.out.println(dis.readUTF());
Yes, you are right. The content written by 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);
}
Eldest brother, this char type has been forcibly changed to byte type, which is out of accuracy. No wonder it can't come back, so don't be greedy for convenience when using it, and honestly change to dos. write ("Hello". getBytes ()); Everything is fine
DataOutputStream writes txt file data garbled
This is normal. If you want to read it, you should read it with DataInputStream. If you want to keep it as a text file, you should directly use FileOutputStream or PrintWriter
OutputStreamWriter oStreamWriter = new OutputStreamWriter(new FileOutputStream(file), "utf-8");
oStreamWriter.append(str);
oStreamWriter.close();
The main reason is that there are different coding methods
To use a character stream instead of a byte stream
The BufferedReader class reads text from the character input stream and buffers characters to efficiently read characters, arrays, and lines