Concept

How can you write binary data to an output file?

ComputerScienceOne / File Output

"Just as with binary input, it is best to use a class that abstracts the file type and data so that we don’t have to deal with the low-level details of the binary data. However, if necessary, binary output can be done using a FileOutputStream. Typically, you can load all your data into a byte array and dump it all at once.\n\nbyte data[] = ...;\n\ntry (FileOutputStream fos =\n\nnew FileOutputStream(new File(\"outfile.bin\")) ){\n\nfos.write(data);\n\n} catch(IOException ioe) {\n\nthrow new RuntimeException(ioe);\n\n}\n\nThis example uses a try-with-resources statement so the FileOutputStream will automatically be closed for us. You could wrap a FileOutputStream in a BufferedWriter, but it will likely not gain you anything in terms of performance. A buffered output stream is better if your writes are frequent and “small.” Here small means smaller than the size of the buffer (BufferedWriter is typically 8KB). Writing several individual integer values for example would be better done by buffering them and writing them all at once. In our example, we simply wanted to dump a bunch of data, likely more than 8KB in practice, all at once. Moreover, using a BufferedWriter would lose us the ability to write raw byte data."

Related Ideas

How can you write binary data to an output file? | ComputerScienceOne | Bifalgorithm | Bifalgorithm