Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java InputStream to ByteBuffer

I am reading dds textures, but since once built the jar I can't access those textures through url and file and have to use InputStream instead.

So I would need to know how I can obtain a java.​nio.ByteBuffer from an java.io.InputStream.

Ps: no matter through 3rd part libraries, I just need it working

like image 983
elect Avatar asked May 04 '15 08:05

elect


People also ask

How do you write InputStream to ByteArrayOutputStream?

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() .

How do you read all bytes from InputStream?

Since Java 9, we can use the readAllBytes() method from InputStream class to read all bytes into a byte array. This method reads all bytes from an InputStream object at once and blocks until all remaining bytes have read and end of a stream is detected, or an exception is thrown.

How do you convert bytes to ByteBuffer?

In short, to make a conversion between a ByteBuffer and a byte array you should: Create a byte array and wrap it into a ByteBuffer. The buffer's capacity and limit will be the array's length and its position will be zero. Retrieve the bytes between the current position and the limit of the buffer.


1 Answers

For me the best in this case is 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().

UPDATE: as long as you have the byte array, as @Peter pointed, you have to convert to ByteBuffer

ByteBuffer.wrap(bytes) 

JAVA 9 UPDATE: as stated by @saka1029 if you're using java 9+ you can use the default InputStream API which now includes InputStream::readAllBytes function, so no external libraries needed

InputStream is; byte[] bytes = is.readAllBytes() 
like image 89
Jordi Castilla Avatar answered Oct 01 '22 08:10

Jordi Castilla