我在PostgreSQL表上有一个包含bytea数据类型的表。
我正在尝试使用JDBC结果集从bytea数据中编写和检索pdf文件。
但是,在检索文件后尝试显示文件时文件已损坏。
这是我的代码:
private void insertBytea(java.io.File file) {
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
Logger.getLogger(BeteaTest.class.getName()).log(Level.SEVERE, null, ex);
}
try {
java.sql.Connection connectDB = java.sql.DriverManager.getConnection("jdbc:postgresql://localhost:5433/funsoft", "postgres", "xxx");
connectDB.setAutoCommit(false);
java.sql.PreparedStatement pstmt = connectDB.prepareStatement("INSERT INTO test_binary (test_bytea) VALUES(?)");
java.io.FileInputStream fis;
try {
fis = new java.io.FileInputStream(file);
pstmt.setBinaryStream(1, fis, (int) file.length());
pstmt.executeUpdate();
connectDB.commit();
pstmt.close();
java.sql.PreparedStatement pstmtR = connectDB.prepareStatement("SELECT * FROM test_binary LIMIT 1");
// pstmtR.setString(1, file.getName());
java.sql.ResultSet rs = pstmtR.executeQuery();
while (rs.next()) {
byte[] imgBytes = rs.getBytes(2);
//java.io.InputStream ios = rs.getBinaryStream(2);
java.io.ByteArrayInputStream byteaStream = new java.io.ByteArrayInputStream(imgBytes);
java.io.File tempFile;
try {
tempFile = java.io.File.createTempFile("REP" + com.afrisoftech.lib.DateLables.getDateLabel() + "_", ".pdf");
java.io.FileOutputStream fileIS = new java.io.FileOutputStream(tempFile);
fileIS.write(imgBytes);
fileIS.close();
// this is where i am trying to display the file
com.afrisoftech.lib.PDFRenderer.renderPDF(tempFile);
} catch (IOException ex) {
Logger.getLogger(BeteaTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
try {
fis.close();
} catch (IOException ex) {
ex.printStackTrace();
Logger.getLogger(BeteaTest.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(BeteaTest.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (SQLException ex) {
ex.printStackTrace();
Logger.getLogger(BeteaTest.class.getName()).log(Level.SEVERE, null, ex);
}
}