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 do fread and fwrite read and write binary data?ComputerScienceOne · Binary Files
- How do you write and read binary data in C?ComputerScienceOne · Closing Files
- How do buffered and unbuffered file input/output differ?ComputerScienceOne · Buffered and Unbuffered
- When should you use specialized classes for binary file input?ComputerScienceOne · File Input
- When should data be stored as binary or text files?ComputerScienceOne · Buffered and Unbuffered
- When should data be stored in binary or text file format?ComputerScienceOne · Binary vs Text Files
- How does try-with-resources simplify closing file input resources?ComputerScienceOne · File Input
- How can a Scanner read input from a file?ComputerScienceOne · File Input