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

我想使用java下载以bytea格式存储的文件。 我没有超级用户权限。 使用下面的代码我下载hex编码文件并将其转换为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 

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