3

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?

3
  • Are you absolutely sure the type_file is of type bytea? The behaviour you describe sounds like the column is defined as oid Commented Aug 30, 2012 at 12:15
  • yes 100% im sure the type_file is the cloumn name of the bytea datatype Commented Aug 30, 2012 at 12:17
  • Possible duplicate of How to download bytea column as file using Java Commented Oct 13, 2015 at 17:50

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

do you have any idea, that how to implement this?
1

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"));
    //....

2 Comments

Q: "How do I do this in Javascript?" A: "Not sure, but here is how you do it using jQuery". There's no spring tag in that question.
@oligofren So what? It's another way, which works. Don't go answer-nazi for nothing, dude ;) Cheers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.