Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/mercurial/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从Java中blob的内容创建文件的代码段_Java_Jdbc_Blob - Fatal编程技术网

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

从Java中blob的内容创建文件的代码段,java,jdbc,blob,Java,Jdbc,Blob,我在Oracle9的数据库blob列中存储了一些文件 我想将这些文件存储在文件系统中 这应该很容易,但我找不到合适的剪子 我如何在java中做到这一点 PreparedStatement ptmst = ... ResutlSet rs = pstmt.executeQuery(); rs.getBlob(); // mistery FileOutputStream out = new FileOutputStream(); out.write(); // etc et c 我知

我在Oracle9的数据库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作为inputstream获取,并将其内容转储到outputstream。所以“痛苦”应该是这样的:

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工作,您可能会考虑使用来处理细节。那么,设置流之后的所有内容都将是:

IOUtils.copy(in, out);

还有另一种方法可以更快地完成相同的操作。实际上,上面的答案很好,但是像
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

编辑


很抱歉,没有看到最初文章中的编辑部分。

使用Oracle XML DB和Java带来了一些美好的回忆。