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

13,187

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/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.

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

Share:
13,187
Tony Stark
Author by

Tony Stark

Updated on June 13, 2022

Comments

  • Tony Stark
    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
    vpram86 over 14 years
    Ah! Just late by a second. Good one! :)
  • Jon Skeet
    Jon Skeet over 14 years
    There's no need to use DataOutputStream here.
  • vpram86
    vpram86 over 14 years
    Could you explain me why? Anyway, I just said that he could use it.:)
  • Joachim Sauer
    Joachim Sauer over 14 years
    If 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
    Joachim Sauer over 14 years
    Actually 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
    Otto Allmendinger over 14 years
    just 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
    Joachim Sauer over 14 years
    I 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
    Stephen C over 14 years
    @Joachim: I know. It is an example.