在使用Java编写PDF文件后,PDF文件被破坏

时间:2014-01-08 18:04:13

标签: java

我正在使用hibernate使用以下代码将pdf文件作为字节插入数据库。

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);

然后我试图将文件从数据库写入pdf文件。使用以下代码。但是pdf正在腐败。

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();

我在使用此代码时遇到了什么问题?

1 个答案:

答案 0 :(得分:2)

pdf文件是二进制文件,你应该使用BLOB而不是CLOB。

另外,当您从文件中读取内容时,您需要使用类似DataInputStream.readFully的内容来确保您正在阅读所有数据。