Scala Files.readAllBytes
Write a small binary payload and read one byte as an unsigned value.
A simple example
Files.readAllBytes
- Start with Two bytes, 0 and 7
- Do this Write and read the bytes
- Result 0, 7
Syntax
Files.readAllBytes(preset)
Run these examples in Scala
Save one example at a time as Lesson.scala. Use Scala 2.13 on JDK 21.
scalac Lesson.scala
scala LessonRecover the brightest setting from a preset
A camera club stores three brightness levels in a compact binary preset. Read the saved bytes back and display the brightest setting as an unsigned number on the familiar 0–255 scale.
import java.nio.file.Files
import java.nio.file.Path
object Lesson {
def main(args: Array[String]): Unit = {
val base = Files.createTempDirectory("lesson-")
try {
val preset = Files.write(base.resolve("preset"), Array[Byte](0, 64, -1))
println(java.lang.Byte.toUnsignedInt(Files.readAllBytes(preset).last))
} finally {
val tree = Files.walk(base)
try tree.sorted(java.util.Comparator.reverseOrder[Path]()).forEach(p => Files.delete(p))
finally tree.close()
}
}
}
255
The final byte has all eight bits set and represents 255.
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?
Read the first locker state
A desk stores two status values in a compact file. Read the unsigned byte at the indicated zero-based offset. Which stored sample is returned?
What to watch for
Text encoding can change byte values. Use binary I/O for this format.