Code snippet for creating a file from the contents of a blob in Java
•
Java
I have some files stored in the blob column of the database in Oracle 9
I want to store those files in the file system
It should be easy, but I didn't find the right clip
How do 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 like this... I don't know what was commented as mistery
thank you
edit
I finally got this question from David
This is my lazy realization:
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();
}
Solution
You need to take the blob as the input stream and dump its contents to the output stream So "suffering" should be like this:
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,len);
}
If you find yourself doing a lot of such IO work, you can see the details of using Apache commons io Then, all the contents after setting the stream are as follows:
IoUtils.copy(in,out);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
