Retrieving file from bytea in PostgreSQL using java

时光毁灭记忆、已成空白 提交于 2019-12-06 07:39:09

问题


Hi I'm using the below code to retrieve the file from the postgresql bytea using java, but inside the file I'm getting numbers like 314530413142313141

File file = new File("c:/test.doc");
FileOutputStream fos = new FileOutputStream(file);
ResultSet rs = st.executeQuery("SELECT * FROM test_bytea where id=" + 1);
        if (rs != null) {
            while (rs.next()) {

                byte[] fileBytes = new byte[1024];
                InputStream is = rs.getBinaryStream("type_file");
                while (is.read(fileBytes) > 0) {
                    fos.write(fileBytes);
                }

                // use the stream in some way here
            }
            rs.close();
        }    

Please let me know what goes wrong in my code?


回答1:


The data is escaped ( starts with \x and then is hexadecimal two chars for each byte) this is what comes out of a bytea field. you need to unescape it before storing it in the file.




回答2:


Instead of doing it manually, you can use Spring:

ResultSet rs = st.executeQuery("SELECT * FROM test_bytea where id=" + 1);
if (rs != null) {
    LobHandler lobHandler = new DefaultLobHandler();
    byte[] myFile = lobHandler.getBlobAsBytes(rs, "type_file"));
    //....


来源:https://stackoverflow.com/questions/12196123/retrieving-file-from-bytea-in-postgresql-using-java

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