如何使用Java将bytea列下载为文件 [英] How to download bytea column as file using Java

查看:431
本文介绍了如何使用Java将bytea列下载为文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Java下载bytea格式存储的文件.我没有超级用户权限.使用下面的代码,我下载了十六进制编码的文件并将其转换为pdf,但是转换后的pdf已损坏,但是如果我通过终端使用\ copy函数(在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 );`

然后:

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

这篇关于如何使用Java将bytea列下载为文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆