0

I've got a Table where i store my pdf files as blob. I get the InputStream and insert it like this.

pstmt.setBinaryStream(1, inputStream);

For this I created a Model with Integer ID and InputStream blob; as variables.

I read the blob like this out of my DB.

blob.setBlob(rs.getBinaryStream("blob_file"));

Now I tried to create the PDF file again with this.

byte[] buffer = new byte[4096];
        File file= new File("c:\\MyPath\\myPDF.pdf");

        try{
            FileOutputStream output= new FileOutputStream(file);
            int b = 0;
            while ((b = blob.getBlob().read()) != -1) {
                output.write(buffer);

            }
            output.close();
        }catch(IOException ex){
            System.err.println("Blob Error: "  + ex.getMessage());
        }

With this method I get a corrupt PDF file which I can't open.

I found an alternative which worked very well like this.

IOUtils.copy(blob.getBlob(), output);

But I don't get why my first Version didn't work and what's the difference between These two.

1 Answer 1

1

Try this:

 FileOutputStream output = null;
 InputStream is = blob.getBlob();
 try{
    output= new FileOutputStream(file);
    int b = 0;
    while ((b = is.read(buffer)) != -1) {
        output.write(buffer, 0, b);
    }          
} catch(IOException ex){
    System.err.println("Blob Error: "  + ex.getMessage());
} finally {
   is.close();
   if (output != null) {
       output.close();
   }

}

The problem in your initial code is the fact that you don't use the value of b (which is the the total number of bytes read into the buffer) so you probably write more bytes than you should which is probably the cause of the corruption of your file.

Sign up to request clarification or add additional context in comments.

2 Comments

I think it's the buffer 'byte[] buffer = new byte[4096];' It still don't work with your solution. How can I get the right number for the buffer?
@Ovoxo good catch the second error was is.read() instead of is.read(buffer). Retry with the new code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.