Wednesday, January 29, 2014

Reading/Writing Binary Data

Files, such as images, are not made up of characters but of bytes. A byte is a fundamental storage unit in a computer— a number consisting of eight binary digits.

The Java library has a different set of classes, called streams, for working with binary

files.

Here is a simple example of copying binary data from a web site to a file.

You use an InputStream to read binary data.

URL imageLocation = new URL("http://horstmann.com/java4everyone/duke.gif");
InputStream in = imageLocation.openStream();

To Write binary data to a file, use FileOutputStream

FileOutputStream out = new FileOutputStream("duke.gif");

The read() method of an input stream reads a single byte and returns –1 when no further input is available. 

The write() method of an output stream writes a single byte.

boolean done = false;
while (!done)
{
             int input = in.read(); // -1 or a byte between 0 and 255
             if (input == -1) 
             { 
                     done = true; 
             }
            else 
            { 
                    out.write(input); 
            }

}

No comments:

Post a Comment