Search code examples
javabinarybytedatacontextdataformat

How to write array of bytes to a binary file in Java


How to write an array of bytes b[i] to a binary file in Java.

I need to write those bytes it into a "binary file" to be able to read it later using hex editor (AXE).

Some readers might be confused by "binary file", by binary file I don't mean a file filled by zeros and ones, I mean machine-readable form, something like this : binary files in text editor

The hex editor suppose to read this data, hex editor

From what I understand I need to byte stream that data into a file Is there a command I could use for this purpose.

Any code would be appreciated.


Solution

  • Just write the byte[] to a FileOutputStream pointing to the file:

    private static void writeBytesToFile(byte[] b, String f) {
    
        try (FileOutputStream out = new FileOutputStream(f)){
            out.write(b);
        }
    
        catch (IOException e) {
            e.printStackTrace();
        }          
    }