Errror while retrieving pdf file from mongodb in java

I am using mongodb community version. I stored pdf file with size less than 16 MB in table as follows

         byte[] bytesArray = new byte[(int) file.length()];

        FileInputStream fis = new FileInputStream(file);; //read file into bytes[]
       document.append("binaryFile", new BsonBinary(bytesArray));
        collection.insertOne(new Document(document));   

But at the time of retrial of the pdf file from database I used following code

FindIterable it = collection.find(whereQuery);

        ArrayList<Document> docs = new ArrayList<Document>();


        for (Document doc1: docs) {

            byte[] c = ((org.bson.types.Binary)doc1.get("binaryFile")).getData();
            fileInputStream= new ByteArrayInputStream(c);

At the this time pdf file got created but could not be opened. It displayed following error.

“Error Adobe Reader could not open document.pdf becase it is either not a supported file or because file has damaged”.

Hello @Kavita_Mhatre, welcome to the forum.

Here is code I tried to store a small PDF file ( 213470 bytes) in a document of MongoDB collection. I am using Java 8, MongoDB 4.2 and MongoDB Java Driver 3.12. This worked fine:

// Writing a PDF file to a document
Path file = Paths.get("intro.pdf");
byte [] fileBytes = Files.readAllBytes(file);
System.out.println("File size: " + fileBytes.length);
Binary binData = new Binary(fileBytes); // org.bson.types.Binary class
Document doc = new Document("_id", 1).append("file", binData);

// Reading from document and creating the PDF file
Document doc = collection.find(new Document("_id", 1)).first();
Binary binData = doc.get("file", Binary.class);
byte [] fileBytes =  binData.getData();
System.out.println("File size: " + fileBytes.length);
Path file = Paths.get("new_intro.pdf");
Files.write(file, bytes); // this creates the file