(Java) Write decimal/hex to a file, and not string
Solution 1
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
.
Solution 2
OutputStream os = new FileOutputStream(fileName);
String text = "42";
byte value = Byte.parseByte(text);
os.write(value);
os.close();
Solution 3
There you go http://java.sun.com/javase/6/docs/api/java/io/DataOutputStream.html#writeInt%28int%29
Tony Stark
Updated on June 13, 2022Comments
-
Tony Stark almost 2 years
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)
-
vpram86 over 14 yearsAh! Just late by a second. Good one! :)
-
Jon Skeet over 14 yearsThere's no need to use DataOutputStream here.
-
vpram86 over 14 yearsCould you explain me why? Anyway, I just said that he could use it.:)
-
Joachim Sauer over 14 yearsIf you want to write bytes, then any OutputStream is ok. Only if you want to write ints/longs/floats/doubles/... directly, then you can use a DataOutputStream to do the conversion to bytes for you.
-
Joachim Sauer over 14 yearsActually if you want to write the whole array then "out.write(bytes)" will be ok, you don't need to use the 3-arguments version.
-
Otto Allmendinger over 14 yearsjust as an interesting aside: have a look at the java.util.zip.* classes that provide on-the-fly compression. You can pass them to the DataOutputStream constructor and save quite a lot of disk IO
-
Joachim Sauer over 14 yearsI took the liberty of updating the link to point to a current version of the docs. There are too many links to ancient documentation out there ;-)
-
Stephen C over 14 years@Joachim: I know. It is an example.