JavaRanch Home    
This page:         last edited 02 November 2012         What's Changed?         Edit

Read Doesnt Do What You Think It Does   

A common question when using the IO classes is why this block of code does not work:

File aFile = new File("");
InputStream is = new FileInputStream(aFile);
byte[] data = new byte[aFile.length()];;

The results can be puzzling. If the input file is an image it may be mangled or not display at all. Binary or text data may be incomplete. This is because Read Doesn't Do What You Think It Does. A quick glance at the Java API for gives us the following information:

public int read(byte[] b) throws IOException

Reads some number of bytes from the input stream and stores them 
into the buffer array b. The number of bytes actually read is returned as an integer. . .

The documentation states that read reads "some number" of bytes. It is not guaranteed to fill the byte array. The number of bytes read is returned by the read method. One should use this return value to make sure that he is receiving the data which he expects. A correct usage of read() would be to read chunks of a file and collect them in a buffer like so:

ByteArrayOutputStream buffer = new ByteArrayOutputStream();
File aFile = new File("");
InputStream is = new FileInputStream(aFile);
byte[] temp = new byte[1024];
int read;

while((read = >= 0){
   buffer.write(temp, 0, read);
byte[] data = buffer.toByteArray();
// process the data array . . .

Another option would be the readFully(byte[] b) method declared in the interface. This method will read a number of bytes equal to the size of array b from the input. Both JavaDoc:java.lang.DataInputStream and JavaDoc:java.lang.RandomAccessFile implement JavaDoc:java.lang.DataInput .

There are other examples in the online book Java Platform Performance for those who are curious about how to move data efficiently.


JavaRanchContact us — Copyright © 1998-2014 Paul Wheaton