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

Reading Single Bytes with read()

Master the read() method that returns the next byte as an int (0-255) or -1 at end-of-file.

Reading Single Bytes with read()

You'll learn how to use the read() method to retrieve data one byte at a time from a FileInputStream.

The Core Idea

The read() method is the simplest way to extract data from a FileInputStream. Each call reads one byte from the file and returns it as an int value between 0 and 255. When the stream reaches the end of the file, read() returns -1 to signal there's no more data.

Think of it like reading a book one letter at a time: you get one character, then the next, and eventually you reach "THE END."

Why Return an int Instead of a byte?

Java's byte type is signed (-128 to 127), but file data needs unsigned representation (0 to 255). By returning an int, the method avoids confusion and uses -1 as a clear "end-of-file" marker without overlapping valid byte values.

Basic Usage Pattern

FileInputStream fis = new FileInputStream("data.txt");

int byteValue = fis.read();  // Read one byte

if (byteValue == -1) {
    // End of file reached
} else {
    // byteValue contains 0-255
    byte actualByte = (byte) byteValue;  // Cast if needed
}

fis.close();

Reading Until End-of-File

The typical pattern loops until -1 appears:

FileInputStream fis = new FileInputStream("data.txt");

int byteValue;
while ((byteValue = fis.read()) != -1) {
    // Process each byte
    System.out.print((char) byteValue);  // Example: print as character
}

fis.close();

Key Takeaway: The read() method returns each byte as an int (0-255) and signals end-of-file with -1, making it the fundamental building block for byte-by-byte file reading.