← Java from Scratch Lesson 61 of 88 · 10 XP

FileInputStream

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

FileInputStream reads a file byte by byte:

try (FileInputStream in = new FileInputStream("data.bin")) {
    int b;
    while ((b = in.read()) != -1) {      // read() → 0..255, or -1 at the end of the file
        …
    }
}

byte[] buf = new byte[4096];
int n = in.read(buf);                     // a whole piece at once: how many bytes were read

read() returns an int, not a byte: there are 257 values (0–255 and "the end", −1), and they don't fit into a byte. And a byte in Java is signed (−128…127) — hence b & 0xFF when you need 0–255.

Reading one byte at a time without a buffer is slow: each read() is a call to the system. For speed — BufferedInputStream or reading into an array.

Task. The program has saved the input to the file data.bin. Read it with a FileInputStream and print: the size in bytes, the first 4 bytes in hexadecimal separated by spaces (String.format("%02X", b)) and a checksum — the sum of all the bytes modulo 256.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.