views:

706

answers:

4

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)

+7  A: 

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.

Joachim Sauer
Ah! Just late by a second. Good one! :)
Aviator
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
Otto Allmendinger
+1  A: 

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

Aviator
There's no need to use DataOutputStream here.
Jon Skeet
Could you explain me why? Anyway, I just said that he could use it.:)
Aviator
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
Oh! Okie.. Got it.. thanks!
Aviator
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 ;-)
Joachim Sauer
Okie :).....I understand!
Aviator
A: 

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 :-)

Stephen C
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.
Joachim Sauer
@Joachim: I know. It is an example.
Stephen C
A: 
    OutputStream os = new FileOutputStream(fileName);
    String text = "42";
    byte value = Byte.parseByte(text);
    os.write(value);
    os.close();
ZZ Coder