从Java中的blob的内容创建文件的代码段
发布时间:2020-12-14 16:28:58 所属栏目:Java 来源:网络整理
导读:我有一些文件存储在Oracle 9中的数据库blob列中. 我想把那些文件存储在文件系统中. 这应该很简单,但我没有找到正确的剪辑. 我如何在java中这样做? PreparedStatement ptmst = ... ResutlSet rs = pstmt.executeQuery(); rs.getBlob(); // mistery FileOutpu
我有一些文件存储在Oracle 9中的数据库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作为输入流,并将其内容转储到输出流.所以“苦难”应该是这样的:
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,len); } 如果您发现自己正在做很多这样的IO工作,您可以查看使用Apache Commons IO来处理细节.然后设置流后的所有内容只是: IOUtils.copy(in,out); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |