从 Java 中 blob 的内容创建文件的代码段 [英] Snippet to create a file from the contents of a blob in Java

查看:19
本文介绍了从 Java 中 blob 的内容创建文件的代码段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Oracle 9 的数据库 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.

我如何在 Java 中执行此操作?

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

谢谢

编辑

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

I finally got this derived from David's question.

这是我懒惰的实现:

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 作为输入流并将其内容转储到输出流.所以痛苦"应该是这样的:

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

如果你发现自己做了很多这样的 IO 工作,你可能会考虑使用 Apache Commons IO 照顾细节.然后设置流后的一切都将是:

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

这篇关于从 Java 中 blob 的内容创建文件的代码段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆