Nov 102012
Article Java

This post presents sample java code snippets to write binary data to a file, and exposes the considerations to be taken into account when working with binary data.

Example 1. Using FileOutputStream

The sample code above is maybe the simplest to use to write 256 bytes of data with values from 0 to 255 to a binary file “data.dat”. After compiling an running the code, we can check the contents of the file with the “xxd” command:

Example 2. Using BufferedOutputStream to improve the performance

The example 1 above is fully functional, but every time the write() method is called, an I/O operation to the disk is performed. If we are working with big-sized files, the performance can be greatly improved using a BufferedOutputStream obtained from the FileOutputStream, as in the next example code:

In this case, as can be seen in the example, we must call the flush() method of the BufferedOutputStream before calling the close() method of the FileOutputSstream, to ensure the data remaining in the buffer is written to disk.

Example 3. Using OutputStreamWriter to specify the character encoding to use

If there are non-USASCII characters in the text strings to be written, such as accented characters, the spanish ‘ñ’ character, or the euro symbol  “€”, etc, we might have to specify the character encoding to use in the output file.

The OutputStreamWriter takes care of performing the conversion from the UNICODE encoding used internally in Java to represent text strings, and the external encoding specified at the time an instance of this class is created.

On the other hand, the OutputStreamWriter object can be wrapped in a BufferedWriter object to improve the performance by minimizing the number of disk I/O operations performed.


 Posted by at 8:44 pm

 Leave a Reply