I have a blob column in my database table, for which I have to use byte[]
in my Java program as a mapping and to use this data I have to convert it to InputStream
or OutputStream
. But I don't know what happens internally when I do so. Can anyone briefly explain me what's happening when I do this conversion?
You create and use byte array I/O streams as follows:
byte[] source = ...;
ByteArrayInputStream bis = new ByteArrayInputStream(source);
// read bytes from bis ...
ByteArrayOutputStream bos = new ByteArrayOutputStream();
// write bytes to bos ...
byte[] sink = bos.toByteArray();
Assuming that you are using a JDBC driver that implements the standard JDBC Blob interface (not all do), you can also connect a InputStream
or OutputStream
to a blob using the getBinaryStream
and setBinaryStream
methods1, and you can also get and set the bytes directly.
(In general, you should take appropriate steps to handle any exceptions, and close streams. However, closing bis
and bos
in the example above is unnecessary, since they aren't associated with any external resources; e.g. file descriptors, sockets, database connections.)
1 - The setBinaryStream
method is really a getter. Go figure.