How to download bytea column as file using Java

≡放荡痞女 提交于 2019-12-10 11:46:25

问题


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


来源:https://stackoverflow.com/questions/33107318/how-to-download-bytea-column-as-file-using-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!