Read stream to byte array in Java

Description

The following code shows how to read stream to byte array.

Example


//  w w  w . j  a v  a 2 s  .  c  om
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class Main {
  public static byte[] readBytes(InputStream stream) throws IOException {
    ByteArrayOutputStream b = new ByteArrayOutputStream();
    int readedBytes;
    byte[] buf = new byte[1024];
    while ((readedBytes = stream.read(buf)) > 0) {
      b.write(buf, 0, readedBytes);
    }
    b.close();
    return b.toByteArray();
  }


}




















Home »
  Java Tutorial »
    I/O »




Binary File
Byte Array
CharSet
Checksum
Console
Create Copy Move Delete
Directory
Drive
Encode Decode
File Attribute
File Lock
File System
GZIP
Jar File
NIO Buffer
Path
Scanner
StreamTokenizer
Temporary File
Text File
Zip