Commit 5b17870
committed
feat: add ByteStreamExample demonstrating ByteArrayInputStream usage
WHAT:
- Implemented `ByteStreamExample` to showcase the use of `ByteArrayInputStream`.
- Created a byte array containing characters 'a' through 'j'.
- Read the stream byte by byte until end-of-stream (-1).
- Printed each byte as a character to the console.
- Closed the stream after reading.
WHY:
- `ByteArrayInputStream` allows treating a byte array as an input stream.
- Useful for scenarios where data is available in memory (e.g., buffers, network packets, test data).
- Demonstrates the core principle of Java I/O: unifying different data sources under the InputStream abstraction.
HOW:
1. Declared a byte array (`byte b[]`) initialized with ASCII characters.
2. Wrapped it in a `ByteArrayInputStream` instance.
3. Used a `while` loop to repeatedly call `read()`.
- Each `read()` returns the next byte as an `int` (0–255).
- Converted the byte to a `char` for printing.
- When `read()` returns `-1`, it indicates end of stream.
4. Closed the stream to free resources.
REAL-WORLD USE CASES:
- Testing I/O code without external files (unit tests using in-memory data).
- Reading network or binary data stored temporarily in memory.
- Parsing byte streams from compressed archives or serialized objects.
- Implementing memory-efficient data pipelines.
NOTES:
- `ByteArrayInputStream` does not throw `IOException` on `close()` (it’s a no-op), but calling close is good practice.
- Unlike `FileInputStream`, no external file is needed, making it lightweight.
- Can combine with higher-level streams (e.g., `BufferedInputStream`, `DataInputStream`) for structured reading.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 4c06769 commit 5b17870
1 file changed
+5
-4
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
5 | 5 | | |
6 | 6 | | |
7 | 7 | | |
8 | | - | |
9 | | - | |
10 | | - | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
11 | 12 | | |
12 | 13 | | |
13 | 14 | | |
14 | 15 | | |
15 | | - | |
| 16 | + | |
0 commit comments