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

If I have a file and I want to literally write '42' to it (a value, not a string), which, for example, is 2a in hex, how do I do that? I want 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 an answer on Google, possibly because I don't know the correct search terms)

+2


source to share


4 answers


For writing binary data, you want to use OutputStream

(for example FileOutputStream

).

If you find that your data is written as strings, then you are probably using Writer

(for example, FileWriter

or OutputStreamWriter

wrapped around FileOutputStream

). Anything called " *Writer

" or " *Reader

" refers exclusively to text / String

s. You want to avoid this if you want to write binary data.



If you want to write different data types (not just byte

s) then you will want to look into DataOutputStream

.

+7


source


    OutputStream os = new FileOutputStream(fileName);
    String text = "42";
    byte value = Byte.parseByte(text);
    os.write(value);
    os.close();

      



+2


source


+1


source


If you just want to write bytes, it 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 :-)

0


source







All Articles