Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Snippet to create a file from the contents of a blob in Java

Tags:

java

jdbc

blob

I have some files stored in a database blob column in Oracle 9.

I would like to have those files stored in the file system.

This should be pretty easy, but I don't find the right snipped.

How can I do this in java?

 PreparedStatement ptmst = ...
 ResutlSet rs = pstmt.executeQuery();
 rs.getBlob();
 // mistery 
 FileOutputStream out = new FileOutputStream();
 out.write(); // etc et c

I know it should be something like that... what I don't know is what is commented as mistery

Thanks

EDIT

I finally got this derived from David's question.

This is my lazy implementation:

PreparedStatement pstmt = connection.prepareStatement("select BINARY from MYTABLE");
ResultSet rs = pstmt.executeQuery();
while( rs.next() ) {
    Blob blob = rs.getBlob("BINARY");
    System.out.println("Read "+ blob.length() + " bytes ");
    byte [] array = blob.getBytes( 1, ( int ) blob.length() );
    File file = File.createTempFile("something-", ".binary", new File("."));
    FileOutputStream out = new FileOutputStream( file );
    out.write( array );
    out.close();
}
like image 840
OscarRyz Avatar asked Jul 02 '09 22:07

OscarRyz


People also ask

How do you represent a BLOB in Java?

To represent a BLOB data type, we use K, M, and G characters that represent the multiples of 1024, 1024*1024, 1024*1024*1024, respectively. The lifespan of a BLOB ends when a transaction commits. We should use the BLOB data type if we want to store very large binary values.


2 Answers

You'd want to get the blob as an inputstream and dump its contents to the outputstream. So 'misery' should be something like:

Blob blob = rs.getBlob(column);
InputStream in = blob.getBinaryStream();
OutputStream out = new FileOutputStream(someFile);
byte[] buff = new byte[4096];  // how much of the blob to read/write at a time
int len = 0;

while ((len = in.read(buff)) != -1) {
    out.write(buff, 0, len);
}

If you find yourself doing a lot of IO work like this, you might look into using Apache Commons IO to take care of the details. Then everything after setting up the streams would just be:

IOUtils.copy(in, out);
like image 91
David Winslow Avatar answered Oct 23 '22 14:10

David Winslow


There is another way of doing the same operation faster. Actually the answer above works fine but like IOUtils.copy(in,out) it takes a lot of time for big documents. The reason is you are trying to write your blob by 4KB iteration. Simplier solution :

Blob blob = rs.getBlob(column);
InputStream in = blob.getBinaryStream();
OutputStream out = new FileOutputStream(someFile);
byte[] buff = blob.getBytes(1,(int)blob.getLength());
out.write(buff);
out.close();

Your outputStream will write the blob in one shot.

Edit

Sorry didn't see the Edit section on the intial Post.

like image 1
GiantSteps Avatar answered Oct 23 '22 16:10

GiantSteps