6

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.

4 Answers 4

9

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.

2
  • Ah! Just late by a second. Good one! :)
    – vpram86
    Sep 7, 2009 at 9:18
  • 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 Sep 7, 2009 at 9:32
2
    OutputStream os = new FileOutputStream(fileName);
    String text = "42";
    byte value = Byte.parseByte(text);
    os.write(value);
    os.close();
1

If you just want to write bytes, the following will suffice:

import java.io.*;
...
OutputStream out = new FileOutputStream("MyFile");
try {
    // Write one byte ...
    out.write((byte) 42);
    // Write multiple bytes ...
    byte[] bytes = ...
    int nosWritten = out.write(bytes, 0, bytes.length);

} finally {
    out.close();
}

Exception handling is left as an exercise for the reader :-)

2
  • 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. Sep 7, 2009 at 9:28
  • @Joachim: I know. It is an example.
    – Stephen C
    Sep 7, 2009 at 13:00
1

There you go http://java.sun.com/javase/6/docs/api/java/io/DataOutputStream.html#writeInt%28int%29

4
  • There's no need to use DataOutputStream here.
    – Jon Skeet
    Sep 7, 2009 at 9:19
  • Could you explain me why? Anyway, I just said that he could use it.:)
    – vpram86
    Sep 7, 2009 at 9:21
  • 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. Sep 7, 2009 at 9:26
  • 1
    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 ;-) Sep 7, 2009 at 9:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.