← Java from Scratch
Lesson 62 of 88 · 10 XP
FileOutputStream
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
FileOutputStream writes bytes:
try (FileOutputStream out = new FileOutputStream("data.bin")) { // overwrite
out.write(65); // one byte: 'A'
out.write(new byte[]{1, 2, 3});
out.write("Hello".getBytes(StandardCharsets.UTF_8));
}
new FileOutputStream("data.bin", true) // append to the end
write(int) writes the lowest byte of the number: write(300) writes 300 & 0xFF = 44.
Byte streams are for binary formats: pictures, game saves, network protocols. For text a
Writer is more convenient — it converts characters to bytes by itself.
Task. The input is integers. Write each one to out.bin as one byte (write(n)), then the string
END in UTF-8. Print the size of the file (new File(...).length()) and, after reading the file back
(Files.readAllBytes), its bytes as unsigned numbers separated by spaces (b & 0xFF).
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.