What\'s the difference between writeBytes(str)
vs write(str)
in DataOutputStream
?
And is there any Tips/Tricks to use them?
Thanks in adva
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).
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.