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

我有一些文件存储在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(); } 

您希望将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); 

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

编辑

抱歉没有看到最新发布的编辑部分。