| Refresh | Home EGTry.com

InputStream to byte array


package io;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class InputStream2ByteArray {

	public static void main(String[] args) throws IOException {
		InputStream in=new FileInputStream("/tmp/req.data");
		byte[] data=toByteArray(in);
		in.close();
		FileOutputStream out=new FileOutputStream("/tmp/req2.data");
		out.write(data);
		out.close();
	}

	public static byte[] toByteArray(InputStream in) throws IOException {
		ByteArrayOutputStream out=new ByteArrayOutputStream();
		byte[] buffer=new byte[1024*4];
		int n=0;
		while ( (n=in.read(buffer)) !=-1) {
			out.write(buffer,0,n);
		}
		return out.toByteArray();
	}
}