如何使用Java将bytea列作为文件下载

时间:2015-10-13 15:57:46

标签: java postgresql jdbc psql bytea

我想使用java下载以bytea格式存储的文件。我没有超级用户权限。使用下面的代码我下载十六进制编码文件并将其转换为pdf但转换后的pdf损坏,而如果我使用\ copy函数(不能在java中使用)通过终端复制,下载过程可以顺利进行。

        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

1 个答案:

答案 0 :(得分:0)

根据PostgreSQL JDBC驱动程序documentation中的示例,以下内容对我来说很好:

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