Java Files binary streams
Open sequential byte streams for reading or writing a file.
A simple example
Files binary streams
- Start with Stream containing byte 7
- Do this Read one byte, then read again
- Result 7, then end of stream
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.javaRead 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.
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);
}
}
}
}
250 -1
The first call returns an unsigned byte value. The second reports the end of the input.
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.
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);
}
}
}
}
-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?
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.