ImageIO 垃圾临时文件在工作完成后不会被删除

ImageIO garbage temp files are not deleted after work is done

我正在使用 ImageIO 将文件从 JBIG2 转换为 JPEG,一切正常,但 ImageIO 创建的临时文件没有被删除,而是卡在临时文件夹中。

例如:imageio1278573787994972734.tmp

这会非常困难,我不想 运行 磁盘 space。

有什么想法可以让他在完成后删除这些临时文件吗?

谢谢。

代码如下:

def convertJBig2ToJpeg(j2bigFile: File) : Try[File] = Try {
import java.io._
import net.java.truecommons.shed.ResourceLoan._
loan (new FileInputStream(j2bigFile)) to { inputStream =>
  val disf = new DefaultInputStreamFactory()
  val imageInputStream = disf.getInputStream(inputStream)
  val imageReader = new JBIG2ImageReader(new JBIG2ImageReaderSpi())
  imageReader.setInput(imageInputStream)
  val param = imageReader.getDefaultReadParam
  val bufferedImage = imageReader.read(0, param)
  val newFilePath = j2bigFile.getParent + "/" + j2bigFile.getName.split('.')(0) + "." + MimeType.postfixValue(JPG)
  val newFile = new File(newFilePath)
  try {
    ImageIO.write(bufferedImage, MimeType.postfixValue(JPG), newFile)
  }catch {
    case e: Throwable =>
      Files.deleteIfExists(newFile.toPath)
      throw e
  }
  newFile
}}

当您在读取和写入后没有正确处理资源时会发生这种情况。

遵循这个处理策略来摆脱问题

这是 Java 语法。

处置reader

if(imageReader.getInput() != null && imageReader.getInput() instanceof ImageInputStream)            
  ((ImageInputStream)imageReader.getInput()).close();
imageReader.dispose();

处置作家

try {
     imageWriter.setOutput(out);
     imageWriter.write(null, new IIOImage(image, null, null), iwp);
     out.flush();
 } catch(IOException e) {                        
     imageWriter.abort();                    
     throw e;
 } finally {
     try {                           
         out.close();                            
     } catch(Exception inner) {                              
     }
     imageWriter.dispose();
 }

Scala 中的上述代码

try {
     imageWriter.setOutput(out)
     imageWriter.write(null, new IIOImage(image, null, null), iwp)
     out.flush()
 } catch { 
   case e: IOException =>                        
     imageWriter.abort()                    
     throw e
   case _ => if (imageWriter != null) imageWriter.abort()
 } finally {
     try {                           
         out.close()                         
     } catch {
       case _ =>                              
     }
     imageWriter.dispose()
 }

有关更多信息,请访问 this blog,其中解释相同