Java Files.readAllBytes and write
Move a small binary payload between a byte array and a file.
A simple example
Files.readAllBytes and write
- Start with Two bytes, 0 and 7
- Do this Write and read the bytes
- Result 0, 7
Syntax
public static byte[] readAllBytes(Path path) throws IOException
JDK 21 declarations (4)
public static byte[] readAllBytes(Path path) throws IOExceptionpublic static Path write(Path path, byte[] bytes, OpenOption... options) throws IOExceptionpublic static Path write(Path path, Iterable<? extends CharSequence> lines, Charset cs, OpenOption... options) throws IOExceptionpublic static Path write(Path path, Iterable<? extends CharSequence> lines, OpenOption... options) throws IOException
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaStore a three-level brightness preset
A photography student saves three brightness levels as bytes. The brightest level has all eight bits set, so the viewer must convert that stored byte before displaying its value on a 0–255 scale.
import java.nio.file.*;
class Main {
public static void main(String[] args) throws Exception {
Path desk = Files.createTempDirectory("file-lesson-");
try {
Path preset = desk.resolve("brightness.bin");
Files.write(preset, new byte[]{0, 64, (byte) 255});
byte[] levels = Files.readAllBytes(preset);
System.out.println(levels.length);
System.out.println(Byte.toUnsignedInt(levels[2]));
} finally {
try (var paths = Files.walk(desk)) {
for (Path p : paths.sorted(java.util.Comparator.reverseOrder()).toList())
Files.deleteIfExists(p);
}
}
}
}
3 255
The file contains three bytes. Unsigned conversion recovers the intended value for the last level.
Append a second device sample
A device logs its measurements as individual bytes. When the second sample arrives, append it to the existing data so the first reading remains available for comparison.
import java.nio.file.*;
import java.util.*;
class Main {
public static void main(String[] args) throws Exception {
Path desk = Files.createTempDirectory("file-lesson-");
try {
Path log = Files.write(desk.resolve("samples.bin"), new byte[]{7});
Files.write(log, new byte[]{9}, StandardOpenOption.APPEND);
System.out.println(Arrays.toString(Files.readAllBytes(log)));
} finally {
try (var paths = Files.walk(desk)) {
for (Path p : paths.sorted(java.util.Comparator.reverseOrder()).toList())
Files.deleteIfExists(p);
}
}
}
}
[7, 9]
The explicit append option adds one byte after the original measurement.
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
readAllBytes needs enough memory for the full file. A Java byte is signed, so convert to unsigned when displaying values from 128 to 255.