Java 把文件/目录压缩成zip文件

本文介绍了一个用Java编写的简单文件及文件夹压缩工具。该工具能够读取用户输入的源文件或目录,并将其压缩成.zip格式的文件。支持对单个文件或整个文件夹进行压缩,并能自动确定压缩后的文件名。

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

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class Zipping {

    public static void main(String[] a) throws Exception {
   
        BufferedReader in = new BufferedReader (new InputStreamReader(System.in));
        System.out.println("Enter the source directory/file name : ");
        String source = in.readLine().trim();
        File src = new File (source);
        if (src.isDirectory()) {
            String zipFile = source + ".zip";
            zipFolder (source, zipFile);
        } else {
            int lastDot = source.lastIndexOf(".");
            String zipFile;
            if (lastDot != -1) {
                zipFile = source.substring(0, lastDot) + ".zip";
            } else {
                zipFile = source + ".zip";
            }
            zipFolder (source, zipFile);
        }
    }

    static public void zipFolder(String srcFolder, String destZipFile) throws Exception {
        ZipOutputStream zip = null;
        FileOutputStream fileWriter = null;

        fileWriter = new FileOutputStream(destZipFile);
        zip = new ZipOutputStream(fileWriter);

        addFileToZip("", srcFolder, zip);
        zip.flush();
        zip.close();
    }

    static private void addFileToZip(String path, String srcFile, ZipOutputStream zip) throws

Exception {

        File folder = new File(srcFile);

        if (folder.isDirectory()) {
            addFolderToZip(path, srcFile, zip);
        } else {
            byte[] buf = new byte[1024];
            int len;
            FileInputStream in = new FileInputStream(srcFile);
            zip.putNextEntry(new ZipEntry(path + "/" + folder.getName()));

            while ((len = in.read(buf)) > 0) {
                zip.write(buf, 0, len);
            }
        }
    }

    static private void addFolderToZip(String path, String srcFolder, ZipOutputStream zip)

throws Exception {
        //if ( src.isDirectory()) {
        File folder = new File(srcFolder);
        String[] fileName = folder.list();

        for (int i = 0; i < fileName.length; i++) {

        if (path.equals("")) {
            addFileToZip(folder.getName(), srcFolder + "/" + fileName[i], zip);
        } else {
            addFileToZip(path + "/" + folder.getName(), srcFolder + "/" + fileName[i],

zip);
        }
    }
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值