Advertisement
Advertisement


Convert InputStream to byte array in Java


Question

How do I read an entire InputStream into a byte array?

2014/09/10
1
869
9/10/2014 10:09:09 AM

Accepted Answer

You can use Apache Commons IO to handle this and similar tasks.

The IOUtils type has a static method to read an InputStream and return a byte[].

InputStream is;
byte[] bytes = IOUtils.toByteArray(is);

Internally this creates a ByteArrayOutputStream and copies the bytes to the output, then calls toByteArray(). It handles large files by copying the bytes in blocks of 4KiB.

2015/12/11
1159
12/11/2015 5:33:29 PM


Finally, after twenty years, there’s a simple solution without the need for a 3rd party library, thanks to Java 9:

InputStream is;
…
byte[] array = is.readAllBytes();

Note also the convenience methods readNBytes(byte[] b, int off, int len) and transferTo(OutputStream) addressing recurring needs.

2017/10/18

Use vanilla Java's DataInputStream and its readFully Method (exists since at least Java 1.4):

...
byte[] bytes = new byte[(int) file.length()];
DataInputStream dis = new DataInputStream(new FileInputStream(file));
dis.readFully(bytes);
...

There are some other flavors of this method, but I use this all the time for this use case.

2018/11/15

If you happen to use google guava, it'll be as simple as :

byte[] bytes = ByteStreams.toByteArray(inputStream);
2016/03/20

As always, also Spring framework (spring-core since 3.2.2) has something for you: StreamUtils.copyToByteArray()

2017/04/18

public static byte[] getBytesFromInputStream(InputStream is) throws IOException {
    ByteArrayOutputStream os = new ByteArrayOutputStream(); 
    byte[] buffer = new byte[0xFFFF];
    for (int len = is.read(buffer); len != -1; len = is.read(buffer)) { 
        os.write(buffer, 0, len);
    }
    return os.toByteArray();
}
2018/04/28

Source: https://stackoverflow.com/questions/1264709
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]