Course contentsShow
← Java
Lesson 1916 of 2,87039. File I/O: Basic Byte StreamsFree lesson

Reading into Byte Arrays with read(byte[])

Learn to read multiple bytes at once into a byte array and interpret the return value indicating bytes read.

Reading into Byte Arrays with read(byte[])

What you'll learn: How to read multiple bytes at once from a FileInputStream into a byte array and understand what the return value tells you.

The Core Idea

When working with FileInputStream, reading one byte at a time with read() is like filling a bucket one drop at a time—it works, but it's inefficient. The read(byte[]) method lets you read chunks of data all at once, like dipping a cup into the stream instead of using an eyedropper.

How read(byte[]) Works

You create a byte array of a specific size (your "cup"), and then pass it to read(byte[]). The method fills your array with as many bytes as it can from the stream, up to the array's length.

The crucial detail: read(byte[]) returns an int telling you how many bytes were actually read. This number might be:

  • Equal to your array length (the array was filled completely)
  • Less than your array length (fewer bytes were available, perhaps near the end of the file)
  • -1 (meaning the stream has reached the end—no more data)

Why the Return Value Matters

Think of reading a file with a 1024-byte array. The file might be 2500 bytes long. Your first two reads will return 1024 (array filled), but the third read returns 452 (only 452 bytes left). The fourth read returns -1 (end of stream). If you ignored these return values and assumed the array was always full, you'd process garbage data from previous reads.

Always use the return value to know exactly how many valid bytes are in your array after each read.

Key Takeaway: The read(byte[]) method efficiently reads multiple bytes into an array and returns the number of bytes actually read, or -1 when the stream ends—always check this return value to process only valid data.