How do I convert a java.io.InputStream
to a java.sql.Blob
using pure Java?
In response to tbodt's suggestions, I ran the following through the eclipse debugger. The debugger shows that myinputstream
has content, but that blob
remains null
at the end of the code. What do I need to do to fix this?
byte[] contents;
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int count;
while ((count = myinputstream.read(buffer)) != -1){output.write(buffer, 0, count);}//debugger says myinputstream has blksize 16384, buffcount 12742, and max 127394 here
contents = output.toByteArray();
Blob blob = null;
try {blob = new SerialBlob(contents);}
catch (SerialException e) {e.printStackTrace();}
catch (SQLException e) {e.printStackTrace();}
someObject.setSomeBlobProperty(blob);//debugger says blob is null here
I also ran the IOUtils
approach through the debugger, but got the exact same results, with a null
blob
but a populated myinputstream
. How can I fix this?
Blob blob = null;
try {
blob = new SerialBlob(IOUtils.toByteArray(myinputstream));//debugger says myinputstream has contents here.
someObject.setSomeBlobProperty(blob);//debugger says blob is null here
}
catch (SerialException e) {e.printStackTrace();}
catch (SQLException e) {e.printStackTrace();}
In both cases, the debugger says myinputstream
has blksize
16384, buffcount
12742, and max
127394 at the indicated locations, despite blob
remaining null
. I also checked the underlying MySQL database after running this code and confirmed that the blob field is empty.
I then ran the following through the Eclipse debugger, which showed that the byte[]
called content
remained empty after the attempts to populate it. So the resulting blob
is empty, while the inputstream
does indeed continue to have the same content values as shown above:
Blob blob = null;
byte[] content = IOUtils.toByteArray(myinputstream);
try {
blob = new SerialBlob(content);//debugger says content is empty here
someObject.setSomeBlobProperty(blob);//debugger says blob is empty here.
}//debugger says myinputstream has the same values as in edit#1
catch (SerialException e) {e.printStackTrace();}
catch (SQLException e) {e.printStackTrace();}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…