0
我有一个表格,我将我的pdf文件存储为blob。 我得到InputStream并像这样插入它。Java从数据库中获取Blob并写入
pstmt.setBinaryStream(1, inputStream);
为此,我创建了一个模型Integer ID
和InputStream blob;
为变量。
我从我的数据库中读取这样的blob。
blob.setBlob(rs.getBinaryStream("blob_file"));
现在我试着再次创建PDF文件。
byte[] buffer = new byte[4096];
File file= new File("c:\\MyPath\\myPDF.pdf");
try{
FileOutputStream output= new FileOutputStream(file);
int b = 0;
while ((b = blob.getBlob().read()) != -1) {
output.write(buffer);
}
output.close();
}catch(IOException ex){
System.err.println("Blob Error: " + ex.getMessage());
}
用这种方法我得到一个损坏的PDF文件,我无法打开。
我发现了一个非常好的替代方案。
IOUtils.copy(blob.getBlob(), output);
但我不明白为什么我的第一个版本没有工作,这两者之间有什么区别。大概
FileOutputStream output = null;
InputStream is = blob.getBlob();
try{
output= new FileOutputStream(file);
int b = 0;
while ((b = is.read(buffer)) != -1) {
output.write(buffer, 0, b);
}
} catch(IOException ex){
System.err.println("Blob Error: " + ex.getMessage());
} finally {
is.close();
if (output != null) {
output.close();
}
}
在初始代码的问题是,你不使用b的值(即读入缓冲区的字节总数),所以你:
我认为这是缓冲'byte [] buffer = new byte [4096];'它仍然不适用于您的解决方案。我怎样才能得到正确的缓冲区号码? – Ovoxo
@Ovoxo很好赶上第二个错误是is.read()而不是is.read(buffer)。用新代码重试 –
完美,一切正常!谢谢! – Ovoxo