0

I am using hibernate to insert a pdf file as bytes into database using the below code.

File file = new File("D:\\test.pdf");
byte[] imageData = new byte[(int) file.length()];
FileInputStream fileInputStream = new FileInputStream(file);
fileInputStream.read(imageData);
fileInputStream.close();
emp.setClobdata(new String(imageData));
session.save(emp);

Then I am trying to write the file from database to a pdf file. Using the below code. But the pdf is getting corrupted.

Emp emp = (Emp) session.get(Emp.class, 2);
byte[] b = emp.getClobdata().getBytes();
FileOutputStream fout = new FileOutputStream("D:\\some.pdf");
fout.write(b); fout.flush();

What I am doing wrong with this code?

1
  • Can you say more about your database? Commented Jan 18, 2014 at 3:15

1 Answer 1

2

pdf files are binary, you should be using a BLOB not a CLOB.

also, when you read from the file, you need to use something like DataInputStream.readFully to ensure you are reading all the data.

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

3 Comments

Thanks for your response. I have tried using BLOB in my database. Still issue exists. Could you be bit more specific about DataInputStream.readFully that would really help me.
The updated code is same. All I did was changed the database field type as BLOB. I am experiencing problems with the above mentioned code snippets
@user3173304 - if your code is the same, then you missed a key point. the data is binary, so you should be treating it as bytes exclusively, not chars (or String).

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.