压缩文件io流 java

这篇文章详细描述了一个Java程序,使用`ZipOutputStream`实现对指定文件夹及其内容进行压缩的过程,包括读取文件、创建`ZipEntry`并将其添加到压缩流中。
摘要由CSDN通过智能技术生成
public class Text {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        //确定要压缩文件的路径
        File src=new File("D:\\xx");
        //确定要压缩成的文件路径
        File destparent=src.getParentFile();
        File dest=new File(destparent+src.getName()+".zip");
        //创建压缩流连接要要压缩成的文件路径
        ZipOutputStream zos=new ZipOutputStream(new FileOutputStream(dest));
        toZip(src,zos,src.getName());
        zos.close();
    }
    public static void toZip(File src,ZipOutputStream zos,String name) throws IOException {
        //将要要压缩的文件其内部变成list形式
        File[] files = src.listFiles();
        //遍历list分为文件和非文件两种情况
        for (File file : files) {
            if (file.isFile()){
                //创建压缩后的文件
                ZipEntry ze=new ZipEntry(name+"\\"+file.getName());
                //加入到压缩流中的一个文件位
                zos.putNextEntry(ze);
                //读取原文件的数据并写入到压缩流中
                FileInputStream fis=new FileInputStream(file);
                int i;
                while ((i=fis.read())!=-1){
                    zos.write(i);
                }
                //关闭输入流和压缩流的一个文件位
                fis.close();
                zos.closeEntry();
            }else {
                //递归
                toZip(file,zos,name+"\\"+file.getName());
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值