关于压缩文件后删除源文件的一点问题

近期在项目中,需要压缩文件,同时压缩文件后需要删除源文件,

public static boolean fileToZip(String sourceFilePath,String zipFilePath,String zipFileName){
    boolean flag = false;
    File sourceFile = new File(sourceFilePath);
    FileInputStream fis = null;
    BufferedInputStream bis = null;
    FileOutputStream fos = null;
    ZipOutputStream zos = null;
    if (!sourceFile.exists()){
        log.error("待压缩的文件目录,sourceFilePath={},不存在",sourceFilePath );
    }else {
        try {
            File zipFile = new File(zipFilePath + File.separator + zipFileName + ".zip");
            if (zipFile.exists()){
                log.error("文件已存在,zipFile={}",zipFile );
            } else {
                File[] files = sourceFile.listFiles();
                if (files != null && files.length > 0){
                    fos = new FileOutputStream(zipFile);
                    zos = new ZipOutputStream(new BufferedOutputStream(fos));
                    byte[] bufs = new byte[1024*10];
                    for (File file : files) {
                        //创建zip实体并添加进压缩包
                        ZipEntry zipEntry = new ZipEntry(file.getName());
                        zos.putNextEntry(zipEntry);
                        //读取待压缩的文件, 并写进压缩包
                        fis = new FileInputStream(file);
                        bis = new BufferedInputStream(fis,1024*10);

                        int read = 0;
                        while ((read = bis.read(bufs,0 ,1024*10 )) != -1){
                            zos.write(bufs,0 ,read );
                        }
                        //这句一开始没有,
                        bis.close();
                    }
                    flag = true;
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            //关闭流
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (zos != null) {
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            File[] files = sourceFile.listFiles();
            for (File file : files) {
                //删除源文件
                file.delete();
            }

        }

    }

    return flag;
}

刚开始一直删不掉,也判断是流没有关闭,后来在大佬提示下,

                        fis = new FileInputStream(file);
                        bis = new BufferedInputStream(fis,1024*10);

才明白,我的这两个流,因为是在循环体里面放的,会造成堆栈的孤岛问题, 我每次循环一次就新建了一个input流,导致之前的input流成为栈内存中的孤岛,没有被GC回收,占用了文件,才会一直删不掉,后来在 循环体中 加上

bis.close();

bingo,问题解决

思考: 对于基础的堆栈的不熟悉,导致了这个问题卡了我一下午,有空还是应该多看看java的基础,不能觉得基础不重要!!!!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值