I/O
io2ByteStreams
- Path
- pkg9io/io2ByteStreams.java
- Package
- pkg9io
- Study order
- 2
- Run
- Single-file source launch
- Command
- java pkg9io/io2ByteStreams.java
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg9io;2 3import java.io.BufferedInputStream;4import java.io.BufferedOutputStream;5import java.io.ByteArrayInputStream;6import java.io.ByteArrayOutputStream;7import java.io.FileInputStream;8import java.io.FileOutputStream;9import java.io.IOException;10import java.io.InputStream;11import java.io.OutputStream;12import java.nio.file.Files;13import java.nio.file.Path;14 15/*16 * io2ByteStreams.java17 * -------------------18 * Byte streams: reading/writing raw bytes with InputStream / OutputStream.19 *20 * DEFINITION:21 * Byte streams move 8-bit bytes and are the foundation of all I/O. Use them22 * for binary data (images, audio, files of any kind). For text prefer the23 * character streams in io3.24 *25 * KEY POINTS:26 * - FileInputStream / FileOutputStream talk to files; ByteArray*Stream to memory.27 * - Wrap in Buffered*Stream to batch syscalls and dramatically speed up I/O.28 * - Always use try-with-resources so streams are closed (and flushed).29 * - transferTo() (Java 9+) copies a whole stream in one call.30 */31public class io2ByteStreams {32 33 public static void main(String[] args) throws IOException {34 Path file = Files.createTempFile("io2", ".bin");35 byte[] payload = "Bytes: \u2600\u2764 0123".getBytes();36 37 // WRITE bytes (buffered for speed)38 try (OutputStream out = new BufferedOutputStream(new FileOutputStream(file.toFile()))) {39 out.write(payload);40 } // try-with-resources auto-closes (and flushes) here41 42 // READ bytes back43 try (InputStream in = new BufferedInputStream(new FileInputStream(file.toFile()))) {44 byte[] read = in.readAllBytes(); // Java 9+ convenience45 System.out.println("Read " + read.length + " bytes: " + new String(read));46 }47 48 // Copy one stream into another with transferTo (no manual loop)49 ByteArrayOutputStream sink = new ByteArrayOutputStream();50 try (InputStream src = new ByteArrayInputStream(payload)) {51 long copied = src.transferTo(sink);52 System.out.println("transferTo copied " + copied + " bytes into memory");53 }54 55 // Manual read loop (how buffering works under the hood)56 int total = 0;57 try (InputStream in = new FileInputStream(file.toFile())) {58 byte[] buf = new byte[4];59 int n;60 while ((n = in.read(buf)) != -1) total += n; // -1 signals EOF61 }62 System.out.println("Manual loop counted " + total + " bytes");63 64 Files.deleteIfExists(file);65 }66}