日期:2014-05-19  浏览次数:20685 次

Java Blob 字段转byte[] 数组问题
最近在做一个功能,就是说从数据库(数据库用的是DB2)里取出blob(blob 里存储的是一个zip文件) 数据,然后写到一个新的zip文件然后在解压此zip文件。但是在做到blob转byte[] 的时候报了个错。
com.ibm.db2.jcc.b.SqlException: [jcc][10120][11936][3.50.152] 操作无效:已关闭 Lob。 ERRORCODE=-4470, SQLSTATE=null

下面是我的代码:
package test.from.mau.test;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import test.from.mau.ConnectionFactory;

public class UpZip {
public static void main(String[] args) throws Exception {
// String filePath = upZip();
ByteAndFile bf = new ByteAndFile();
// byte[] b = bf.getBytesFromFile(filePath);
byte[] b = getBytesFromDB();
File f = bf.getFileFromBytes(b, "d://a.zip");
}

private static byte[] getBytesFromDB() {
Connection con = null;
byte[] b = null;
Blob blob = null;
try {
if (con == null || con.isClosed()) {
con = ConnectionFactory.getConnection();
}
con.setAutoCommit(false);
PreparedStatement stmt = con
.prepareStatement("SELECT REPORT_DATA FROM RIS.EX_REPORT_DATA_TBL WHERE STUDY_LID = 844 AND EX_FORMAT = 20");
ResultSet rs = stmt.executeQuery();
con.commit();
while (rs.next()) {
blob = (Blob) rs.getBlob("REPORT_DATA");
}
b = blobToBytes(blob);
} catch (SQLException e) {
e.printStackTrace();
}
return b;
}

private static byte[] blobToBytes(Blob blob) {
 BufferedInputStream is = null;
byte[] bytes = null;
try {
is = new BufferedInputStream(blob.getBinaryStream());
bytes = new byte[(int) blob.length()];
int len = bytes.length;
int offset = 0;
int read = 0;

while (offset < len
&& (read = is.read(bytes, offset, len - offset)) >= 0) {
offset += read;
}

} catch (Exception e) {
e.printStackTrace();
}
return bytes;
// byte[] b = null;
// try {
// if (blob != null) {
// long in = 0;
// b = blob.getBytes(in, (int) (blob.length()));
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
//
// return b;

}