我正在尝试从来自数据库的字节数组创建pdf文件。代码运行正常并创建pdf文件,但我无法打开文件,显示文件已损坏或损坏。在这里,我展示了我的完整代码,请指出我想要改变的内容或实现此类代码的方法是正确的。感谢。
TestPDF:
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class TestPDF {
public static void main(String[] args) throws FileNotFoundException {
String jdbcClassName="com.ibm.db2.jcc.DB2Driver";
String host="hostname",port="50000",db="dbname",dbuser="user",dbpass="pass";
String url="jdbc:db2://"+host+":"+port+"/"+db;
String user=dbuser;
String password=dbpass;
Connection con = null;
InputStream fetchStream = null;
try{
//Load class into memory
Class.forName(jdbcClassName);
//Establish connection
con = DriverManager.getConnection(url, user, password);
PreparedStatement pstmt = con.prepareStatement("select * from tgpoa01.aud_trail_dtl WHERE AUD_TRAIL_REC_ID = '-9223372036798517556'");
ResultSet rs = pstmt.executeQuery();
if(rs.next())
{
fetchStream = rs.getBinaryStream("AUD_TRAIL_MSG_TX");
if(rs.getString("AUD_PRCS_STAGE_CD").equals("CONT")){
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
try {
for (int readNum; (readNum = fetchStream.read(buf)) != -1;) {
bos.write(buf, 0, readNum);
System.out.println("read " + readNum + " bytes,");
}
System.out.println("Byte array is="+bos);
} catch (Exception ex) {
ex.printStackTrace();
}
byte[] bytes = bos.toByteArray();
File someFile = new File("d://Output_File.pdf");
try{
FileOutputStream fos = new FileOutputStream(someFile);
fos.write(bytes);
fos.flush();
fos.close();
}catch(Exception e){
}
}
}
}catch(Exception e){
System.out.println("Exception in getting PDF : "+e);
}
}
}
答案 0 :(得分:0)
您用来从数据库中读取for
的{{1}}循环对我来说有点奇怪。您可以尝试其中一种(完全未经测试的)替代方案:
使用bytes
:
ResultSet.getBinaryStream(...)
使用if ( rs.next() ) {
if ( rs.getString("AUD_PRCS_STAGE_CD").equals("CONT") ) {
File someFile = new File("d://Output_File.pdf");
FileOutputStream fos = new FileOutputStream(someFile);
byte[] buffer = new byte[1];
fetchStream = rs.getBinaryStream("AUD_TRAIL_MSG_TX");
while (fetchStream.read(buffer) > 0) {
fos.write(buffer);
}
fos.close();
}
}
:
ResultSet.getBlob(...)