Java压缩文件

Java压缩文件

直接上代码,不多bb

引入的包

import java.io.*;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream

压缩文件的方法

/**
 * @param root 指定要打包的路径
 * @return 打好压缩包的位值
 */
public static Path compressFiles(Path root) {
//        当前文件夹的名字
    final String rootName = root.toFile().getName();
//        输出的压缩包文件
    final Path zipName = Paths.get(System.getProperty("user.dir") + File.separator + rootName + ".zip");
//        获取zip输出流
    try (ZipOutputStream zos = new ZipOutputStream(new DataOutputStream(new FileOutputStream(zipName.toFile())))) {
//            处理传入文件夹下的所有文件
        Files.walkFileTree(root, new SimpleFileVisitor<>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
//                    获取当前文件的夫目录的名字
                final String parent = file.getParent().getFileName().toString();
//                    压缩包中的文件名字
                String zipFileName = "";
                if (parent.equals(rootName)) {
//                    如果是当前文件夹的文件,名字就是它自己原来的名字	
                    zipFileName = file.toFile().getName();
                } else {
//                    如果是当前文件夹的文件夹下面的文件,名字就是它自己父目录的名字加上它自己的名字	
                    zipFileName = parent + File.separator + file.toFile().getName();
                }
//                    把文件添加到压缩包中
                zos.putNextEntry(new ZipEntry(zipFileName));
//                    获取文件流
                final DataInputStream zis = new DataInputStream(new FileInputStream(file.toFile()));
//                    写入内容到当前文件
                int len;
                final byte[] buff = new byte[1024 * 10];
                while ((len = zis.read(buff)) != -1) {
                    zos.write(buff, 0, len);
                }
//                    关闭当前的文件流
                zis.close();
                return super.visitFile(file, attrs);
            }
        });
    } catch (IOException e) {
        e.printStackTrace();
    }
//  返回压缩好的文件路径
    return zipName;
}

使用

public static void main(String[] args) throws IOException {
//        要压缩文件的路径
    final Path root = Paths.get( System.getProperty("user.dir") + File.separator + "要压缩的文件夹");
//        压缩指定的文件到当前的文件夹下
    final Path path = compressFiles(root);
    System.out.println(path);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值