Bifalgorithm post · Computer science one · File Output

How can you write binary data to an output file?

How can you write binary data to an output file? (Computer science one · File Output) — "Just as with binary input, it is best to use a class that abstracts th…

Ideas in this flowchart

  • Binary output should abstract file details, using FileOutputStream only when necessary.
  • A class that abstracts the file type and data avoids low-level binary details.
  • FileOutputStream can be used when raw binary output is required.
  • Data can typically be loaded into a byte array before writing.
  • The byte array can be dumped to the output file all at once.
  • Try-with-resources automatically closes the FileOutputStream.
  • An IOException can be caught and wrapped in a RuntimeException.
  • Wrapping FileOutputStream in BufferedWriter will likely provide no performance benefit.
  • Buffered output is preferable when writes are frequent and smaller than the buffer.
  • Several individual integer values should be buffered and written together.
  • The example writes a large amount of data, likely more than the typical 8KB buffer, at once.
  • Using BufferedWriter would remove the ability to write raw byte data.
Feed/

How can you write binary data to an output file?

No cover

Channel

Computer science one

1 page

"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."

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.