Skip to content

Commit c834e01

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

File tree

1 file changed

+3
-1
lines changed

1 file changed

+3
-1
lines changed

Section23JavaIOStreams/src/ByteStreamExample1.java

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,13 @@
33
public class ByteStreamExample1 {
44
public static void main(String[] args)throws Exception {
55
byte b[]={'a', 'b','c','d','e','f','g','h','i','j'};
6+
67
ByteArrayInputStream bis = new ByteArrayInputStream(b);
78

89
//Reading all bytes together.
910
String str = new String(bis.readAllBytes());
11+
1012
System.out.println(str);
1113
bis.close();
1214
}
13-
}
15+
}

0 commit comments

Comments
 (0)