JAI , TIF转多张JPG(解决不能删除的资源释放问题)

因为对tif转换完成后的jpg处理后要删除,但是最后几张的资源总是无法释放。之前百度上也一直找不到解决方案。

尝试了两种方法:

第一种是用gc

public static List<File> readerTiff(String tiffPath){
        List<File> list = new ArrayList<File>();
        String filePre = tiffPath.substring(0,tiffPath.lastIndexOf("."));
        FileSeekableStream fss = null;
        RenderedOp op = null;
        try{
            fss = new FileSeekableStream(tiffPath);
            TIFFImageDecoder dec = new TIFFImageDecoder(fss,null);
            JPEGEncodeParam param = new JPEGEncodeParam();
            int page = dec.getNumPages();
            for(int i = 0; i < page; i++){
                RenderedImage render = dec.decodeAsRenderedImage(i);
                File file = new File(filePre + i + ".jpg");
                ParameterBlock pb = new ParameterBlock();
                pb.addSource(render);
                pb.add(file.toString());
                pb.add("JPEG");
                pb.add(param);
                op = JAI.create("filestore", pb);
                list.add(file);
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            try {
                op.dispose();
                fss.close();
//                System.gc();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        
        return list;
    }
    
    public static void main(String[] args) throws Exception{

        List<File> list = readerTiff("D:\\demo\\test.tif");
        //模拟业务处理
        Thread.sleep(5000);
        System.out.println("业务处理结束删除temp");
        for(File f : list){
            f.delete();
        }
    }

如果不调用gc会发现有几张图片是无法删掉的等于delete方法调用无效

但是gc的调用因为不是实时的,如果没有处理业务那几秒那么文件还是无法删除,这里可以把删除说法放在System.gc()后面做实验

finally{
			try {
				op.dispose();
				fss.close();
				System.gc();
				System.out.println("业务处理结束删除temp");
				for(File f : list){
					f.delete();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

  

第二种说是在JAI.create("Stream",FileSeekableStream)时候用流写入文件,删除前吧流关闭,因为读取方法的不同并没有做实验,但是似乎是行得通

第三种与其说是方法,应该说是代码中存在的问题了

op.dispose();不应该放在finally中,只要放在
op = JAI.create("filestore", pb);
后面问题就完美解决了

 

posted @ 2019-07-14 19:50  feixiong1688  阅读(913)  评论(0编辑  收藏  举报