0

I have inserted a file into MySQL database as a byte array:

preparedStatment.setBytes(10, inpStream.toString().getBytes());

I had already gotten the file from the database as a byte array but I'm stuck at getting the actual file's contents. What would be the correct way of doing this?

2
  • 1
    The bytes you got from the database are the file contents. Or do I miss something? Commented Jan 3, 2012 at 14:23
  • Exactly, is the file an image or a pdf or something? Or are you trying to read text out of it? Commented Jan 3, 2012 at 14:25

1 Answer 1

1

This is wrong:

preparedStatment.setBytes(10, inpStream.toString().getBytes());

You are storing the result of the InputStream#toString() as bytes in the DB. The InputStream#toString() does not return the file's contents as you seem to think, instead it returns the default classname@hashcode representation inherited from Object#toString().

You need PreparedStatement#setBinaryStream() instead:

preparedStatement.setBinaryStream(10, inpStream);

Then you can retrieve it by ResultSet#getBinaryStream():

InputStream inpStream = resultSet.getBinaryStream("columnname");

Or if you really need PreparedStatement#setBytes(), then you would need to write the InputStream to a ByteArrayOutputStream the usual way first and then get the bytes by its toByteArray() method. But this is not memory efficient per se.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.