1

I have an InputStream that I know is a PDF that I need to use to update a Blob in Oracle. How can I transform this stream into a BufferedOutputStream, or otherwise update the Blob with this stream information?

Note that I am not allowed to wrap an Oracle class in my code due to the restrictions of the code.

What I've tried so far:

I have already tried using this answer: https://stackoverflow.com/a/1574857/2188082 to connect the streams, but the result is a NullPointerError, because the OutputStream is empty.

The current Query I am trying to run:

pstmt = dbConn.prepareStatement("UPDATE "+ qualTable("document")+" set document_blob ="
                   +" utl_raw.cast_to_raw('"+inStream+"') where document_id = " + documentId);

       pstmt.execute();
       pstmt.close();

I am aware that utl_raw.cast_to_raw may not be the correct oracle method to call for an inStream read, unfortunately I am not as well-versed in Oracle as I would like to be, so I am unaware of the correct cast I should be using.

Community
  • 1
  • 1
Zibbobz
  • 725
  • 1
  • 15
  • 41
  • You've already been commenting on my code to copy data from one stream to another - please include what you've tried so far in your question. – Jon Skeet Oct 29 '13 at 19:05

2 Answers2

3

PreparedStatement.setBlob(parameterIndex, inputStream, length).

Like setString and other setters. No OutputStream, but a length needed.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
  • Would the parameterIndex be the location in the database? Also, would I need to execute this statement, or would it work as-is? – Zibbobz Oct 29 '13 at 19:15
  • Nevermind, I was reminded by rolfl that I need to inclue a ? in my PreparedStatement to make it a parameter. Thank you. :) – Zibbobz Oct 29 '13 at 19:51
1

A typical way to do this is to create a byte[] array and to use it to transfer the data:

byte[] buffer = new byte[4096]; // 4K buffer...
int len = 0;
while ((len = input.read(buffer)) >= 0) {
   output.write(buffer, 0, len);
}
output.flush();

This copies some number of bytes in each loop from the input to the output, until you run out of input.

The size of the buffer is a tunable parameter which yu should test in your environment to see what works best.

rolfl
  • 17,539
  • 7
  • 42
  • 76
  • Unfortunately, this returns a null error to me because the output stream is empty. – Zibbobz Oct 29 '13 at 19:23
  • 1
    I see that your question alludes to this. Two things: As Joop suggests, use a positional prepared statement (see `?` parameters when creating prepared statements), and also find out why the output stream is null/closed, it should not be. – rolfl Oct 29 '13 at 19:27
  • Your reminder to include a ? parameter has saved the day. Thank you both. :) – Zibbobz Oct 29 '13 at 19:50