我有一些文件存储在Oracle 9中的数据库blob列中.
@H_404_2@我想把那些文件存储在文件系统中.
@H_404_2@这应该很简单,但我没有找到正确的剪辑.
@H_404_2@我如何在java中这样做?
PreparedStatement ptmst = ... ResutlSet rs = pstmt.executeQuery(); rs.getBlob(); // mistery FileOutputStream out = new FileOutputStream(); out.write(); // etc et c@H_404_2@我知道这应该是这样的…我不知道是什么被评论为mistery @H_404_2@谢谢 @H_404_2@编辑 @H_404_2@我终于得到这个来自大卫的问题. @H_404_2@这是我的懒惰实现:
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(); }
解决方法
您需要将blob作为输入流,并将其内容转储到输出流.所以“苦难”应该是这样的:
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); }@H_404_2@如果您发现自己正在做很多这样的IO工作,您可以查看使用Apache Commons IO来处理细节.然后设置流后的所有内容只是:
IoUtils.copy(in,out);