3

javaを使ってbytea形式で保存されたファイルをダウンロードしたいです。スーパーユーザー権限がありません。以下のコードを使用して、16 進数でエンコードされたファイルをダウンロードして 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
4

1 に答える 1

1

PostgreSQL JDBC ドライバーのドキュメントの例に基づいて、次のようにするとうまくいきます。

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);
}
于 2015-10-13T17:38:36.977 に答える