Bookmark Topic Watch Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Report post to moderator
A common question when using the IO classes is why this block of code does not work:



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 JavaDoc:java.io.InputStream gives us the following information:





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:



Another option would be the readFully(byte[] b) method declared in the
JavaDoc:java.io.DataInput 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.


JavaIoFaq
 
    Bookmark Topic Watch Topic
  • New Topic