18

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

我想将这些文件存储在文件系统中。

这应该很容易,但我找不到合适的剪断。

我怎样才能在java中做到这一点?

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

我知道它应该是这样的......我不知道是什么被评论为神秘

谢谢

编辑

我终于从大卫的问题中得到了这个。

这是我的懒惰实现:

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

2 回答 2

26

您希望将 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, 0, len);
}

如果你发现自己做了很多这样的 IO 工作,你可能会考虑使用Apache Commons IO来处理细节。那么设置流之后的一切都只是:

IOUtils.copy(in, out);
于 2009-07-02T22:58:41.340 回答
1

还有另一种方法可以更快地完成相同的操作。实际上上面的答案很好用,但就像IOUtils.copy(in,out)大文件需要很多时间一样。原因是您试图通过 4KB 迭代来编写您的 blob。更简单的解决方案:

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

您的 outputStream 将一次性写入 blob。

编辑

抱歉没有看到初始帖子的编辑部分。

于 2012-12-27T10:33:23.557 回答