1

I khave some doubt about how convert a Blob object (taken from a database and representing a PDF) into a ByteArrayInputStream object.

So I know that I can do something like this:

ByteArrayOutputStream docPDF = null;
InputStream blobinstream = null;

Blob blob = rset.getBlob("PDF");    // I obtain it from a result set DB query

if(blob!=null) {
    blobinstream = blob.getBinaryStream();
    int chunk = 1024;
    byte[] buffer = new byte[chunk];
    int length = -1;

    docPDF = new ByteArrayOutputStream();

    while ((length = blobinstream.read(buffer)) != -1) {
        docPDF.write(buffer, 0, length);
    }

    docPDF.flush();

So in the previous code snippet I obtained the Blob object from a DB query and I read it obtaining the ByteArrayOutputStream docPDF.

Then I do something like this to convert my ByteArrayOutputStream docPDF into a ByteArrayInputStream object:

ByteArrayInputStream currentPdfBAIS = new ByteArrayInputStream(docPDF.toByteArray());

So I have obtained my ByteArrayInputStream object.

It works fine but it is the best way to do it? Can I obtain a ByteArrayInputStream object starting from a Blob object without passing through the ByteArrayOutputStream docPdf object ? Or the previous presented solution is the right one?

Tnx

  • Why do you want a ByteArrayInputStream? Do you want to keep the InputStream past the transaction in which you create the blob? If not, just use blob.getBinaryStream(). – Adrian Leonhard Feb 23 '15 at 11:58
  • The answer to this question depends on the ultimate destination of the PDF content. Normally you would not ever load it into a byte array because that will not scale very well. – Steve C Feb 23 '15 at 12:23
  • 1
    @AdrianLeonhard Because I am using iText to create a PDF (starting from the content of a Blob into my DB) and iText use a ByteArrayOutputStream to create the PDF –  Feb 23 '15 at 13:18
  • If it uses a ByteArrayOutputStream to create the PDF, why do you want to create a ByteArrayInputStream? I suggest you include the code you are using to create your pdf as that is your actual problem. – Adrian Leonhard Feb 23 '15 at 13:26

1 Answers1

-2

When you get the Input Stream you need to write it to something, so your above example is okay. Bear in mind that you are reading the entire file into memory. If this is the desired outcome then it is fine.

In order to simplify my code I use Apache's IOUtils:

bos = new ByteArrayOutputStream();
IOUtils.copy(rs.getBlob(1).getBinaryStream(), bos);
bos.flush();
byte[] contentData = bos.toByteArray();
Johan Prins
  • 112
  • 5