Library contents

Java Files binary streams

Open sequential byte streams for reading or writing a file.

A simple example

Files binary streams

  1. Start with Stream containing byte 7
  2. Do this Read one byte, then read again
  3. Result 7, then end of stream
The first read consumes the only byte. The next reports the end.

Syntax

Java syntax
public static InputStream newInputStream(Path path, OpenOption... options) throws IOException
JDK 21 declarations (2)
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Read a scanner's one-byte status code

A warehouse scanner writes one numeric status byte for a package. The receiving program needs to tell the status value apart from the point where the scanner file has no more bytes.

First output line250
Main.java
import java.nio.file.*;

class Main {
    public static void main(String[] args) throws Exception {
        Path desk = Files.createTempDirectory("file-lesson-");
        try {
            Path scan = desk.resolve("scan.bin");
            try (var out = Files.newOutputStream(scan)) { out.write(250); }
            try (var in = Files.newInputStream(scan)) {
                System.out.println(in.read());
                System.out.println(in.read());
            }
        } finally {
            try (var paths = Files.walk(desk)) {
                for (Path p : paths.sorted(java.util.Comparator.reverseOrder()).toList())
                    Files.deleteIfExists(p);
            }
        }
    }
}
Output
250
-1

The first call returns an unsigned byte value. The second reports the end of the input.

Advertisements

Detect an empty device response

A kiosk receives a response file with no payload after a cancelled scan. Open it as a binary stream and check the first read before trying to interpret an absent status code.

Result-1
Main.java
import java.nio.file.*;

class Main {
    public static void main(String[] args) throws Exception {
        Path desk = Files.createTempDirectory("file-lesson-");
        try {
            Path result = Files.createFile(desk.resolve("response.bin"));
            try (var input = Files.newInputStream(result)) { System.out.println(input.read()); }
        } finally {
            try (var paths = Files.walk(desk)) {
                for (Path p : paths.sorted(java.util.Comparator.reverseOrder()).toList())
                    Files.deleteIfExists(p);
            }
        }
    }
}
Output
-1

The stream signals end of input immediately. Zero would be a real byte value.

Read a display preset

A museum sign saves three brightness levels as individual bytes. Read the unsigned byte at the indicated zero-based offset. Which stored sample is returned?

Given12 · 80 · 200 | offset 2
Worked result200

What to watch for

InputStream.read returns an int so it can represent each byte as well as the end-of-file marker of minus one.

Documentation for Files binary streams