If I have a file, and I want to literally write '42' to it (the value, not the string), which for example is 2a in hex, how do I do it? I want to be able to use something like outfile.write(42) or outfile.write(2a) and not write the string to the file.
(I realize this is a simple question but I can't find the answer of google, probably because I don't know the correct search terms)
For writing binary data you'll want to use a OutputStream
(such as a FileOutputStream
).
If you find that your data is written as strings, then you're probably using a Writer
(such as a FileWriter
or a OutputStreamWriter
wrapped around a FileOutputStream
). Everything named "*Writer
" or "*Reader
" deals exclusively with text/String
s. You'll want to avoid those if you want to write binary data.
If you want to write different data types (and not just plain byte
s), then you'll want to look into the DataOutputStream
.
OutputStream os = new FileOutputStream(fileName);
String text = "42";
byte value = Byte.parseByte(text);
os.write(value);
os.close();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With