writeBytes(str) vs write(str) in DataOutputStream

后端 未结 2 989
死守一世寂寞
死守一世寂寞 2021-01-24 09:01

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

相关标签:
2条回答
  • 2021-01-24 09:37

    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).

    0 讨论(0)
  • 2021-01-24 09:49

    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.

    0 讨论(0)
提交回复
热议问题