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.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Forget about FileWriter, DataOutputStream for a moment.
OutputStreamandInputStreamclasses. They handlebyte[].ReaderandWriterclasses. They handleStringwhich 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
chars are 16 bit.