java——压缩文件或者文件夹

本文介绍如何使用Java实现文件压缩,并解决中文文件名称乱码问题。通过自定义压缩流程,确保文件和文件夹能正确压缩并保存为.zip格式。详细解释了根据文件类型(目录或文件)进行不同处理的方法,以及设置文件编码以避免乱码。

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

<pre name="code" class="java">/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.zxs.wode;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.Adler32;
import java.util.zip.CRC32;
import java.util.zip.CheckedOutputStream;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;

/**
 * 压缩文件或文件夹
 * 使用org.apache.tools.zip.ZipEntry而不用java.util中自带的,原因:不能解决中文乱码问题
 * @author zhao
 */
public class ZipCompressor {
    /*
     * description 根据传递过来的路径名称,压缩为源文件路劲的zip格式压缩文件
     * return 压缩后文件路劲名
     */
    public String compressExe(String fileName) throws IOException{
        String destFileName=null;
         try {
        File file=new File(fileName);
        //根据文件是目录还是文件确定目标文件的路径
        if(file.isDirectory()){
            destFileName=fileName+".zip";
        }else{
            int m=fileName.indexOf(".");
            if(m != -1){
                destFileName=fileName.substring(0,m)+".zip";
            }else{
                destFileName=fileName+".zip";
            }
        }
            OutputStream os = new FileOutputStream(destFileName);
            //CheckedOutputStream cos=new CheckedOutputStream(os,new CRC32());
             CheckedOutputStream cos=new CheckedOutputStream(os,new Adler32());//两种不同的算法
            ZipOutputStream out=new ZipOutputStream(cos);
            //解决中文文件夹或文件 的文件名称 乱码问题
            out.setEncoding(System.getProperty("sun.jnu.encoding"));
            String basedir="";
            compressFirstDirectory(file,out,basedir);
            out.close();
            cos.close();
            os.close();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(ZipCompressor.class.getName()).log(Level.SEVERE, null, ex);
        }
        return destFileName;
    }
/*
 * 判断文件是目录还是文件,分别调用不同的方法
 */
    private void compressByType(File file, ZipOutputStream out, String basedir) throws IOException {
          if(file.isDirectory()){
              this.compressDirectory(file,out,basedir);
          }else{
              this.compressFile(file,out,basedir);
          }
    }
/*
 * 压缩文件,将源文件中的内容读取,写入到压缩文件中
 */
    private void compressFile(File file, ZipOutputStream out, String basedir) throws IOException {
       if(!file.exists()){
           return ;
       }
        try { 
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
            ZipEntry entry=new ZipEntry(basedir+file.getName());
           // System.out.println(basedir+file.getName());
             //System.out.println(file.getName());
            out.putNextEntry(entry); 
            byte [] b=new byte[8192];
            int count;
            while((count = bis.read(b))!= -1){
                out.write(b, 0, count);
            }
            bis.close();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(ZipCompressor.class.getName()).log(Level.SEVERE, null, ex);
        }
       
    }
    /*
     * 文件第一次为目录时,不存放最外层的目录文件夹
     */
    private void compressFirstDirectory(File file,ZipOutputStream out,String basedir) throws IOException{
        if(!file.exists()){
            return ;
        }
        if(file.isDirectory()){
        File [] files=file.listFiles();
              for(int i =0;i<files.length;i++){
                   this.compressByType(files[i], out, basedir);
              }
        }else{
            this.compressFile(file,out,basedir);
        }
    }
/*
 * 文件是目录时
 */
    private void compressDirectory(File file, ZipOutputStream out, String basedir) throws IOException {
        if(!file.exists()){
            return ;
        }
              File [] files=file.listFiles();
              for(int i =0;i<files.length;i++){
                   this.compressByType(files[i], out, basedir+file.getName()+"/");
              }
    }
    public static void main(String [] args) throws IOException{
        ZipCompressor zc=new ZipCompressor();
        zc.compressExe("f:/18");
    }
}



学习java编程,除了最基本的增,删,改,查功能,常用的就有文件压缩功能,现在我们就来学习java——文件压缩吧!微笑

文件压缩需要使用到的工具:使用org.apache.tools.zip.ZipEntry而不用java.util中自带的,原因:不能解决中文乱码问题

主要思路:根据传入的文件路径名建立以crc32算法的zip输出流,根据传入文件路径名是目录还是文件进行判断,是文件则写入zip中,是目录则遍历到文件并写入zip文件中。

代码如上:

因为工作需求,解压后不包括源文件目录直接进入到里面的文件,因此增加了(文件第一次为目录时,不存放最外层的目录文件夹)内容,自己测试一下看效果就懂了!希望能帮到你们!微笑

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值