在 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();
}
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.
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
Thanks
EDIT
I finally got this derived from David's question.
This is my lazy implementation:
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();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您希望将 blob 作为输入流并将其内容转储到输出流。 所以“痛苦”应该是这样的:
如果你发现自己做了很多这样的 IO 工作,你可能会考虑使用 Apache Commons IO 来处理细节。 那么设置流后的一切都将是:
You'd want to get the blob as an inputstream and dump its contents to the outputstream. So 'misery' should be something like:
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) 一样,对于大文档来说需要花费很多时间。 原因是您正在尝试通过 4KB 迭代写入 blob。 更简单的解决方案:
您的输出流将一次性写入 blob。
编辑
抱歉,没有看到初始帖子的编辑部分。
There is another way of doing the same operation faster. Actually the answer above works fine but like
IOUtils.copy(in,out)
it takes a lot of time for big documents. The reason is you are trying to write your blob by 4KB iteration. Simplier solution :Your outputStream will write the blob in one shot.
Edit
Sorry didn't see the Edit section on the intial Post.