Create PDF using byte array from database
<p>I am trying to create pdf file from byte array which is coming from database.The code runs fine and create the pdf file but I cant open the file it shows that file is corrupted or damaged. Here I show my full code, please point out what I want to change or which way is correct to achieve this type of code. Thanks.</p>

<p><strong>TestPDF:</strong></p>

<pre><code>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);
    }


}
}
</code></pre>