How to download bytea column as file using Java

2019-05-30 20:36发布

问题:

I want to download files stored in bytea format using java. I don't have superuser privileges. Using the code below I download the hex encoded file and convert it to pdf but the converted pdf is damaged whereas if I copy using \copy function(cannot use in java) via terminal, downloading process works smoothly.

        String sql = "(SELECT encode(f,'hex') FROM test_pdf where id='2' LIMIT 1)";
        System.out.println(sql);

        CopyManager copyManager = new CopyManager((BaseConnection) conn);

        FileWriter filew = new FileWriter("/home/sourabh/image.hex");
        copyManager.copyOut("COPY "+sql+"  TO STDOUT ", filew );`

And then :

xxd -p -r image.hex > image.pdf

回答1:

Based on the example in the documentation for the PostgreSQL JDBC driver, the following works fine for me:

try (
        Connection conn = DriverManager.getConnection(
            "jdbc:postgresql://localhost/linkedDB?user=postgres&password=whatever");
        Statement st = conn.createStatement();
        ResultSet rs = st.executeQuery("SELECT f FROM test_pdf WHERE id='2'");
        FileOutputStream fos = new FileOutputStream("C:/Users/Gord/Desktop/retrieved.pdf")) {
    rs.next();
    byte[] fileBytes = rs.getBytes(1);
    fos.write(fileBytes);
} catch (Exception e) {
    e.printStackTrace(System.err);
}