How can I write/read a string from a binary file?
I've tried using writeUTF
/ readUTF
(DataOutputStream/DataInputStream) but it was too much of a hassle.
Thanks.
How can I write/read a string from a binary file?
I've tried using writeUTF
/ readUTF
(DataOutputStream/DataInputStream) but it was too much of a hassle.
Thanks.
If you want to write text you can use Writers and Readers.
You can use Data*Stream writeUTF/readUTF, but the strings have to be less than 64K characters long.
prints
Forget about FileWriter, DataOutputStream for a moment.
OutputStream
andInputStream
classes. They handlebyte[]
.Reader
andWriter
classes. They handleString
which can store all kind of text, as it internally uses Unicode.The crossover from text to binary data can be done by specifying the encoding, which defaults to the OS encoding.
new OutputStreamWriter(outputStream, encoding)
string.getBytes(encoding)
So if you want to avoid
byte[]
and use String you must abuse an encoding which covers all 256 byte values in any order. So no "UTF-8", but maybe "windows-1252" (also named "Cp1252").But internally there is a conversion, and in very rare cases problems might happen. For instance
é
can in Unicode be one code, or two,e
+ combining diacritical mark right-accent'
. There exists a conversion function (java.text.Normalizer) for that.One case where this already led to problems is file names in different operating systems; MacOS has another Unicode normalisation than Windows, and hence in version control system need special attention.
So on principle it is better to use the more cumbersome byte arrays, or ByteArrayInputStream, or java.nio buffers. Mind also that String
char
s are 16 bit.