Java JPA从oracle数据库中检索blob作为其原始文件类型

问题描述 投票:0回答:1

我正在使用java spring和jpa,我有一个查询从Oracle数据库中检索Blob。我得到了斑点,如果它是文本文件,则可以将其下载到我的本地计算机上很好-但是,如果它是图像,则必须通过BufferedImage,并且我仍在处理PDF。到目前为止,我只是通过获取文件的扩展名来查看文件的扩展名,该文件名也存储在数据库中,然后过滤扩展名的字符串。当我得到PDF时,它说文件已损坏或在另一个窗口中打开,但不是。到目前为止,这是我的代码,试图将blob从DB转换为文件:

  Blob blob = Service.retrieveBlob(ID);
    if (blob == null){
      return false;
    }
    String fileName = Service.getFileName(ID);
    String extension = fileName.substring(fileName.lastIndexOf('.') + 1);
    System.out.println(extension);
    if (extension.equals("jpg") || (extension.equals("png"))){
      File file = new File("./DBPicture.png");
      try(FileOutputStream outputStream = new FileOutputStream(file)) {
        BufferedImage bufferedImage = ImageIO.read(blob.getBinaryStream());
        ImageIO.write(bufferedImage, "png", outputStream);
        System.out.println("Image file location: "+file.getCanonicalPath());
      } catch (IOException e) {
        e.printStackTrace();
      }
}
    else {
      InputStream ins = blob.getBinaryStream();
      byte[] buffer = new byte[ins.available()];
      ins.read(buffer);

      File targetFile = new File("./" + fileName);
      OutputStream outStream = new FileOutputStream(targetFile);
      outStream.write(buffer);
}

java spring oracle jpa blob
1个回答
0
投票

available就是这样。它不一定是流的长度。

尝试类似的东西

InputStream ins = blob.getBinaryStream();
File targetFile = new File("./" + fileName);
OutputStream outStream = new FileOutputStream(targetFile);

byte[] buffer = new byte[8000];
int count = 0;
while ((count = ins.read(buffer)) != -1) {
    outStream.write(buffer);
}

// then close your output
outStream.close (); 
© www.soinside.com 2019 - 2024. All rights reserved.