Problem in retrieving PDF file from database
Hello,
I am saving a PDF File into database using Blob.I want to retrieve and write it into PDF file,but I am getting blank page.
I have the code here:
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.PreparedStatement;
publicclass PDFFile{
Connection con;
Statement st;
ResultSet rs;
PreparedStatement pst;
Blob blob;
InputStream input;
OutputStream output;
PDFFile(){
try{
Class.forName("net.sourceforge.jtds.jdbc.Driver");
con = DriverManager.getConnection("jdbc:jtds:sqlserver://192.168.1.20:1433/FlexiReports","sa","madmax");
}catch (ClassNotFoundException cnf){
cnf.printStackTrace();
}catch (java.sql.SQLException sql){
sql.printStackTrace();
}
}
publicvoid insertFile(){
FileReader fr;
File file;
try{
file=new File("c:/testPDFFile.pdf");
fr=new FileReader(file);
pst = con.prepareStatement("insert into Reports values(?)");
pst.setCharacterStream(1,fr,(int)file.length());
pst.executeUpdate();
}
catch (Exception e){
e.printStackTrace();
}
}
publicvoid openFile(){
try{
st = con.createStatement();
rs = st.executeQuery("select fileData from Reports");
int i = 1;
blob =null;
while (rs.next()){
blob = rs.getBlob("fileData");
}
input = blob.getBinaryStream();
output=new FileOutputStream("c:/FromDatabase.pdf");
byte by[]=blob.getBytes(0,(int)blob.length());
output.write(by);
}catch (Exception e){
e.printStackTrace();
}finally{
try{
con.close();
}catch (java.sql.SQLException sqle){
}
}
}
publicstaticvoid main(String args[]){
PDFFile obj=new PDFFile();
obj.insertFile();
obj.openFile();
}
}
You can take Pdf file as input and change the name in insertFile.Let me know if there is any other way of doing it.
I tried some other examples which have typecated result set to OracleResultSet and retrive and write to new file,but using that I get an error,because I am using jtds driver.

