Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(Java) Write decimal/hex to a file, and not string

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)

like image 399
Tony Stark Avatar asked Sep 07 '09 09:09

Tony Stark


2 Answers

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/Strings. 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 bytes), then you'll want to look into the DataOutputStream.

like image 106
Joachim Sauer Avatar answered Oct 26 '22 00:10

Joachim Sauer


    OutputStream os = new FileOutputStream(fileName);
    String text = "42";
    byte value = Byte.parseByte(text);
    os.write(value);
    os.close();
like image 33
ZZ Coder Avatar answered Oct 26 '22 01:10

ZZ Coder