微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

从Java中的blob的内容创建文件的代码段

我有一些文件存储在Oracle 9中的数据库blob列中.

我想把那些文件存储在文件系统中.

这应该很简单,但我没有找到正确的剪辑.

我如何在java中这样做?

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

我知道这应该是这样的…我不知道是什么被评论为mistery

谢谢

编辑

我终于得到这个来自大卫的问题.

这是我的懒惰实现:

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);
}

如果您发现自己正在做很多这样的IO工作,您可以查看使用Apache Commons IO来处理细节.然后设置流后的所有内容只是:

IoUtils.copy(in,out);

原文地址:https://www.jb51.cc/java/125302.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐