Java Array Streams

Previous
Next

ByteArrayInputStream  

  • It is an implementation of an input stream that uses a byte array as the source.
  • This class has two constructors, each of which requires a byte array to provide the data source:

                        ByteArrayInputStream(byte array[ ]) 
                        ByteArrayInputStream(byte array[ ], int start, int numBytes)

  • Here, array is the input source.
  • The second constructor creates an InputStream from a subset of your byte array that begins with the character at the index specified by start and is numBytes long.
import java.io.*; 
class ByteArrayInputStreamDemo { 
	public static void main(String args[]) throws IOException { 
		String tmp = "abcdefghijklmnopqrstuvwxyz"; 
		byte b[] = tmp.getBytes(); 			
ByteArrayInputStream bais1 = new ByteArrayInputStream(b); 	
		ByteArrayInputStream bais2= new ByteArrayInputStream(b,3,3);
		
		ByteArrayOutputStream baos1= new ByteArrayOutputStream();					ByteArrayOutputStream baos2= new ByteArrayOutputStream();	
		int ch;
		while((ch=bais1.read())!=-1){
			baos1.write(ch);
		}
		while((ch=bais2.read())!=-1) {
			baos2.write(ch);
		}
		byte b1[]=baos1.toByteArray();			
byte b2[]=baos2.toByteArray();
        		
		System.out.println("b1 array contents");
		for(int i=0;i<b1.length;i++){
			System.out.print((char)b1[i]);
		}
		System.out.println("b2 arrray contents :");
		for(int i=0;i<b2.length;i++){
			System.out.print((char)b2[i]);
		}
	}
}
Previous
Next

Add Comment

Courses Enquiry Form