简体   繁体   中英

How to download bytea column as file using Java

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM