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

查看:460
本文介绍了用于从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

谢谢

编辑

我终于得到了David的问题。

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天全站免登陆