Stream to byte array

Source: Internet
Author: User

First, the easiest way to write. Using Native Io, one byte reads one byte:

// One character to read, too slow int I; while (I = in. Read ())! =-1) {I = in. Read (); arr [J ++] = I ;}

This method is very slow and is not recommended.

Second, one read:

byte[] arr = new byte[in.available()];in.read(arr);

This is the opposite of the first one. When reading a stream at a time, this situation will occupy a lot of memory when the file is slightly larger, and is not recommended.

Third, buffer read:

byte[]buff = new byte[1024];int eachlength = 0;int total = 0;while((eachlength = in.read(buff)) != -1){    System.arraycopy(buff, 0, arr, total, eachlength);    total += eachlength;}

In this way, 1024 bytes are read each time and then copied to the target array of arr.

Fourth, with commons-io:

org.apache.commons.io.IOUtils.toByteArray(input)

The implementation in the source code is:

public static byte[] toByteArray(InputStream input)  throws IOException{  ByteArrayOutputStream output = new ByteArrayOutputStream();  copy(input, output);  return output.toByteArray();}public static int copy(InputStream input, OutputStream output)  throws IOException{  long count = copyLarge(input, output);  if (count > 2147483647L) {    return -1;  }  return (int)count;}public static long copyLarge(InputStream input, OutputStream output)  throws IOException{  byte[] buffer = new byte[4096];  long count = 0L;  int n = 0;  while (-1 != (n = input.read(buffer))) {    output.write(buffer, 0, n);    count += n;  }  return count;}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.