27

Not sure about how I am supposed to do this. Any help would be appreciated

user398371
  • 857
  • 2
  • 10
  • 15
  • Since ByteArrayInputStream are construct from byte[] http://stackoverflow.com/questions/2163644/in-java-how-can-i-convert-an-inputstream-into-a-byte-array-byte http://stackoverflow.com/questions/1264709/convert-inputstream-to-byte-in-java – h3xStream Aug 16 '10 at 18:22
  • What exactly are you doing with images where you wouldn't be using the `javax.imageio` classes? – Powerlord Aug 16 '10 at 18:59
  • Uploading to Amazon S3... The Java library I'm using required ByteArrayInputStream for all non-string based data – user398371 Aug 17 '10 at 15:45

4 Answers4

30

Read from input stream and write to a ByteArrayOutputStream, then call its toByteArray() to obtain the byte array.

Create a ByteArrayInputStream around the byte array to read from it.

Here's a quick test:

import java.io.*;

public class Test {


       public static void main(String[] arg) throws Throwable {
          File f = new File(arg[0]);
          InputStream in = new FileInputStream(f);

          byte[] buff = new byte[8000];

          int bytesRead = 0;

          ByteArrayOutputStream bao = new ByteArrayOutputStream();

          while((bytesRead = in.read(buff)) != -1) {
             bao.write(buff, 0, bytesRead);
          }

          byte[] data = bao.toByteArray();

          ByteArrayInputStream bin = new ByteArrayInputStream(data);
          System.out.println(bin.available());
       }
}
naikus
  • 24,302
  • 4
  • 42
  • 43
18

You can use org.apache.commons.io.IOUtils#toByteArray(java.io.InputStream)

InputStream is = getMyInputStream();
ByteArrayInputStream bais = new ByteArrayInputStream(IOUtils.toByteArray(is));
Jaroslav
  • 867
  • 12
  • 19
  • 1
    why `IOUtils.toByteArray(is)` instead of `is.readAllBytes()` ? – mathiasfk Feb 05 '20 at 19:01
  • 1
    @mathiasfk no specific reason, just force of habit (never tried the other) – Jaroslav Feb 06 '20 at 14:37
  • 1
    EDIT: because it is available only since Java 9, and I was using 7 / 8 (https://www.tutorialspoint.com/when-to-use-the-readallbytes-method-of-inputstream-in-java-9 ) – Jaroslav Nov 07 '22 at 07:55
4

Or first convert it to a byte array, then to a bytearrayinputstream.

File f = new File(arg[0]);
InputStream in = new FileInputStream(f);
// convert the inpustream to a byte array
byte[] buf = null;
try {
    buf = new byte[in.available()];
    while (in.read(buf) != -1) {
    }
} catch (Exception e) {
    System.out.println("Got exception while is -> bytearr conversion: " + e);
}
// now convert it to a bytearrayinputstream
ByteArrayInputStream bin = new ByteArrayInputStream(buf);
anvarik
  • 6,417
  • 5
  • 39
  • 53
0

Using Kotlin and org.apache.commons.io.IOUtils v2 is simple like that:

IOUtils.toByteArray(is).inputStream()

I guess is the same way in Java too.

zyc
  • 344
  • 3
  • 7