Skip to content

Commit 5b17870

Browse files
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

File tree

1 file changed

+5
-4
lines changed

1 file changed

+5
-4
lines changed

Section23JavaIOStreams/src/ByteStreamExample.java

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,12 @@ public static void main(String[] args) throws Exception {
55
byte b[]={'a', 'b','c','d','e','f','g','h','i','j'};
66
ByteArrayInputStream bis = new ByteArrayInputStream(b);
77

8-
int x; //Reading byte bye byte. one at a time
9-
while((x=bis.read())!=-1)
10-
{
8+
int x;
9+
10+
//Reading byte bye byte. one at a time.
11+
while((x = bis.read())!=-1) {
1112
System.out.print((char)x);
1213
}
1314
bis.close();
1415
}
15-
}
16+
}

0 commit comments

Comments
 (0)