tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Articles > Java > Basics > How to convert InputStream to Byte Array

How to convert InputStream to Byte Array 

The following example shows reading the content from an InputStream as Byte Array.

File Name  :  
com/bethecoder/articles/basics/ins2bytea/InputStream2ByteArrayTest.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.articles.basics.ins2bytea;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Arrays;

public class InputStream2ByteArrayTest {

  /**
   @param args
   */
  public static void main(String[] args) {

    InputStream ins = InputStream2ByteArrayTest.class
        .getClassLoader().getResourceAsStream("ABC.txt");
    
    byte [] streamAsBytes = stream2Bytes(ins);
    
    System.out.println(Arrays.toString(streamAsBytes));
    System.out.println(new String(streamAsBytes));
  }

  public static byte[] stream2Bytes(InputStream ins) {

    byte [] availableBytes = new byte [0];
    
      try {
          byte [] buffer = new byte[4096];
          ByteArrayOutputStream outs = new ByteArrayOutputStream();
          
          int read = 0;
          while ((read = ins.read(buffer)) != -) {
            outs.write(buffer, 0, read);
          }
          
          ins.close();
          outs.close();
          availableBytes = outs.toByteArray();
          
      catch (Exception e) { 
        e.printStackTrace();
      }
      
      return availableBytes;
  }
}
   

It gives the following output,
[65, 66, 67, 32, 65, 66, 67, 32, 65, 66, 67, 13, 10, 65, 66, 67, 32, 65, 
66, 67, 32, 65, 66, 67, 13, 10, 65, 66, 67, 32, 65, 66, 67, 32, 65, 66, 67]

ABC ABC ABC
ABC ABC ABC
ABC ABC ABC



 
  


  
bl  br