Binary Stream Example Code

01
of 01

Java Code:

There are two program listings for reading and writing a binary file byte by byte. The first version shows the need to close the streams manually before Java 7 was released. The second version takes advantage of the try with resources feature that takes care of closing resources for you. Although these listings work it worth noting that this is not the best way to go about reading and writing a binary file. This kind of low level I/O is rare these days - it's much better to use a buffered approach. It is more efficient and faster than processing a file byte by byte.

Note: Remember to change the input constant to point to the path of a binary file on your computer.

The article that goes with these code listings it Reading and Writing Byte Streams.

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class BinaryStreamsV1 {

    // The two constants below specify the input and output jpg files.
    // Change the path and filenames to match jpeg files on your computer.
    private static final String ORIGINAL_FILENAME = "C:\\example.jpg"; 
    private static final String COPY_FILENAME = "C:\\anewexample.jpg";

    public static void main(String[] args) throws IOException {

        FileInputStream fileInput = null;
        FileOutputStream fileOutput = null;

        try 
        {
            //Open the input and out files for the streams
            fileInput = new FileInputStream(ORIGINAL_FILENAME);
            fileOutput = new FileOutputStream(COPY_FILENAME);
            int data;

            //For each byte read it in from the input file
            //and write it to the output file
            //When the end of the file is reached a 
            //value of -1 is returned.
            while ((data = fileInput.read()) != -1) {
                fileOutput.write(data);
            }
        }
        catch (IOException e)
        {
            //Catch the IO error and print out the message
            System.out.println("Error message: " + e.getMessage());
        }    
         finally 
        {
            //Must remember to close streams
            //Check to see if they are null in case there was an
            //IO error and they are never initialized
            if (fileInput != null)
            {
                fileInput.close();
            }
            if (fileInput != null)
            {
                fileOutput.close();
            }
        }
        
    }

}

Version 2 of the program below shows how the try with resources feature of Java 7 can make the code a lot nicer. By specifying the resources being used in the try block you can get rid of the finally block that closes the input and output streams. It means you don't have to worry about closing the input and output streams and so the resources will always be freed up. Also check out the Java 7's new NIO.2 filesystem api that makes interacting with the filesystem faster and more efficient.

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class BinaryStreamsV2 {

    // The two constants below specify the input and output jpg files.
    // Change the path and filenames to match jpeg files on your computer.
    private static final String ORIGINAL_FILENAME = "C:\\example.jpg"; 
    private static final String COPY_FILENAME = "C:\\anewexample.jpg";

    public static void main(String[] args) throws IOException {

        //The new try with resources feature of Java 7 means handling resources is 
        //much easier. All you need to do is initialize them at the start of the try block and it will
        //handle their closure.
        try ( FileInputStream fileInput = new FileInputStream(ORIGINAL_FILENAME);
            FileOutputStream fileOutput = new FileOutputStream(COPY_FILENAME)){
            
            int data;

            //For each byte read it in from the input file
            //and write it to the output file
            //When the end of the file is reached a 
            //value of -1 is returned.
            while ((data = fileInput.read()) != -1) {
                fileOutput.write(data);
            }
        }
        catch (IOException e) //Catch the IO error and print out the message
        {
            System.out.println("Error message: " + e.getMessage());
        }    

        
    }

}