JAVA实现压缩文件的方法(使用java.util.zip.*)

本文介绍了两种使用Java实现的文件和目录压缩方法。一种是使用GZIP算法压缩单个文件,另一种是将整个目录打包成ZIP文件。通过示例代码展示了如何读取源文件、压缩数据并将其保存到目标文件中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

     以下是两个摘自《java examples in a nutshell》的两个方法,挺简单的。

 

 

    /** Gzip the contents of the from file and save in the to file. */
    public static void gzipFile(String from, String to) throws IOException {
        // Create stream to read from the from file
        FileInputStream in = new FileInputStream(from);
        // Create stream to compress data and write it to the to file.
        GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(to));
        // Copy bytes from one stream to the other
        byte[  ] buffer = new byte[4096];
        int bytes_read;
        while((bytes_read = in.read(buffer)) != -1)
            out.write(buffer, 0, bytes_read);
        // And close the streams
        in.close( );
        out.close( );
    }

    /** Zip the contents of the directory, and save it in the zipfile */
    public static void zipDirectory(String dir, String zipfile)
        throws IOException, IllegalArgumentException {
        // Check that the directory is a directory, and get its contents
        File d = new File(dir);
        if (!d.isDirectory( ))
            throw new IllegalArgumentException("Compress: not a directory:  " +
                                               dir);
        String[  ] entries = d.list( );
        byte[  ] buffer = new byte[4096];  // Create a buffer for copying
        int bytes_read;

        // Create a stream to compress data and write it to the zipfile
        ZipOutputStream out =
            new ZipOutputStream(new FileOutputStream(zipfile));

        // Loop through all entries in the directory
        for(int i = 0; i < entries.length; i++) {
            File f = new File(d, entries[i]);
            if (f.isDirectory( )) continue;        // Don't zip sub-directories
            FileInputStream in = new FileInputStream(f); // Stream to read file
            ZipEntry entry = new ZipEntry(f.getPath( ));  // Make a ZipEntry
            out.putNextEntry(entry);                     // Store entry
            while((bytes_read = in.read(buffer)) != -1)  // Copy bytes
                out.write(buffer, 0, bytes_read);
            in.close( );                                  // Close input stream
        }
        // When we're done with the whole loop, close the output stream
        out.close( );
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值