简体   繁体   中英

writeBytes(str) vs write(str) in DataOutputStream

What's the difference between writeBytes(str) vs write(str) in DataOutputStream ? And is there any Tips/Tricks to use them? Thanks in advance.

DataOutputStream belongs to the OutputStream classes for writing binary data - not Writer for text, It is an old class and writeBytes(String) is a weird twitter method as it:

Each character in the string is written out, in sequence, by discarding its high eight bits. If no exception is thrown, the counter written is incremented by the length of s.

So from every Unicode UTF-16 char (16 bits) the low byte is taken. If the string restricted to 7-bits ASCII, maybe a bit ISO-8859-1, the string is not mangled. But in general information is lost.

There is no counterpart in DataInputStream, no String readBytes() .

I would call it a design mishap, as java introduced a separatation from text and binary data ( byte[] ), introducing byte and reserving String and 16-bit char for Unicode text. The author probably felt a need for a C style write(char*) .

No need to mention writeUTF and DataInputStream.readUTF.

write() writes a byte[] to the stream, whereas writeBytes() writes the output of yourString.getBytes() to the stream. If we needed a string from the byte[] we could String yourString = new String(yourByteArray);

As you can see with a String it matters little which approach we use, we can convert to the correct object.

However what if you wanted to send binary data? You probably have a byte[] or a ByteArrayOutputStream , that you can use to write to your data stream directly.

In DataOutputStream , in reference to the oracle documentation ( http://docs.oracle.com/javase/7/docs/api/java/io/DataOutputStream.html ) there isn't any method named write(String) but only write(byte[]) , write(byte[] b, int off, int len) and write(int b) . So, if you have a String , the simplest method you can use is writeBytes(String) .

There is no difference between those methods, only use the proper one according to your needs (the type of the object your data are stored in).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM