YouTip LogoYouTip

Java Bytearrayinputstream

# Java ByteArrayInputStream Class [![Image 3: Java Stream](#) Java Stream](#) * * * The byte array input stream creates a byte array buffer in memory, and the data read from the input stream is stored in this byte array buffer. There are several ways to create a byte array input stream object. Create by accepting a byte array as a parameter: ByteArrayInputStream bArray = new ByteArrayInputStream(byte [] a); Another way to create it is by accepting a byte array and two integer variables `off` and `len`. `off` represents the first byte to read, and `len` represents the length of bytes to read. ByteArrayInputStream bArray = new ByteArrayInputStream(byte []a, int off, int len) After successfully creating a byte array input stream object, you can refer to the methods in the following list to perform read operations or other operations on the stream. | No. | Method Description | | --- | --- | | 1 | **public int read()** Reads the next data byte from this input stream. | | 2 | **public int read(byte[] r, int off, int len)** Reads up to `len` data bytes from this input stream into the byte array. | | 3 | **public int available()** Returns the number of bytes that can be read from this input stream without blocking. | | 4 | **public void mark(int read)** Sets the current mark position in the stream. | | 5 | **public long skip(long n)** Skips `n` input bytes from this input stream. | ### Example The following example demonstrates the use of ByteArrayInputStream and ByteArrayOutputStream: import java.io.*;public class ByteStreamTest { public static void main(String args[])throws IOException { ByteArrayOutputStream bOutput = new ByteArrayOutputStream(12); while( bOutput.size()!= 10 ) { // Get user input value bOutput.write(System.in.read()); } byte b [] = bOutput.toByteArray(); System.out.println("Print the content"); for(int x= 0 ; x < b.length; x++) { // Print character System.out.print((char)b + " "); } System.out.println(" "); int c; ByteArrayInputStream bInput = new ByteArrayInputStream(b); System.out.println("Converting characters to Upper case " ); for(int y = 0 ; y < 1; y++ ) { while(( c= bInput.read())!= -1) { System.out.println(Character.toUpperCase((char)c)); } bInput.reset(); } }} The compilation and running result of the above example is as follows: asdfghjkly Print the content a s d f g h j k l y Converting characters to Upper case A S D F G H J K L Y * * Java Stream](#)
← Java DatainputstreamJava Exceptions β†’