Commit c834e01
committed
feat: add ByteStreamExample1 using ByteArrayInputStream with readAllBytes()
WHAT:
- Implemented `ByteStreamExample1` to demonstrate reading all bytes from a
`ByteArrayInputStream` at once.
- Created a byte array of characters ('a' through 'j').
- Used `readAllBytes()` to retrieve the entire byte stream in a single call.
- Converted the byte array into a String for display.
- Closed the stream after reading.
WHY:
- `readAllBytes()` (Java 9+) provides a convenient way to consume the entire
contents of a stream at once, instead of looping byte-by-byte.
- Demonstrates how in-memory byte arrays can be efficiently turned into
strings or processed as a whole.
- Simplifies scenarios where the data size is small and known in advance.
HOW:
1. Declared a byte array containing ASCII characters 'a' through 'j'.
2. Passed it to a `ByteArrayInputStream` to simulate an input stream source.
3. Called `readAllBytes()`, which:
- Reads all remaining bytes from the stream until end-of-stream.
- Returns them as a new byte array.
4. Wrapped the result in a `String` constructor to convert to a readable string.
5. Printed the string (`abcdefghij`) to the console.
6. Explicitly closed the stream (though `ByteArrayInputStream`'s `close()`
is effectively a no-op).
REAL-WORLD USE CASES:
- Reading in-memory binary data (e.g., network packets, cached files).
- Parsing test data without external file dependencies.
- Simplifying conversions of byte streams to Strings in small/medium-size inputs.
- Useful in mocking InputStreams for unit testing I/O-heavy code.
NOTES:
- `ByteArrayInputStream` supports `mark()` and `reset()` operations fully.
- Best for small datasets since `readAllBytes()` loads everything into memory at once.
- For very large streams, prefer reading in chunks with a buffer.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 5b17870 commit c834e01
1 file changed
+3
-1
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
3 | 3 | | |
4 | 4 | | |
5 | 5 | | |
| 6 | + | |
6 | 7 | | |
7 | 8 | | |
8 | 9 | | |
9 | 10 | | |
| 11 | + | |
10 | 12 | | |
11 | 13 | | |
12 | 14 | | |
13 | | - | |
| 15 | + | |
0 commit comments