Search code examples
mongodbgridfsmongo-javamongo-java-driver

How to get data as byte[] using GridFS Java API?


I am using Java-driver 2.13. GridFS takes input as File, InputStream or byte[] in createFile() method on GridFS instance to create GridFSInputFile .

But when I tried to fetch data back I do have option only as File or outputStream using GridFSDBFile.writeTo() method.

I want to get data as byte[]. Is there any direct way in GridFS API or I need to manually convert it?


Solution

  • There is no direct method that returns a byte[] array, but you can use a ByteArrayOutputStream to achieve a similar effect:

    GridFSDBFile file = ...
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    file.writeTo(baos);
    byte[] bytes = baos.toByteArray();
    

    To avoid unnecessary memory allocation, you can pass an initial size to the ByteArrayOutputStream constructor based on the length of the GridFS file, but note that the length is a long while the ByteArrayOutputStream constructor takes an integer. You can also subclass ByteArrayOutputStream to get direct access to its protected buf field, as the toByteArray method does create a copy of the internal buffer.