java.util.zip

(一)压缩单个文件

 public static void main(String[] args) {
        //压缩单个文件
        //要压缩的文件路径
        String filepath="D:\\markavip\\测试.txt";
        //文件压缩之后的路径
        String zippath="D:\\markavip\\test.zip";
        zipFile(filepath,zippath);
    }

    public static void zipFile(String filepath,String zippath){
        InputStream input=null;
        //压缩
        ZipOutputStream zipOut=null;
        try{
            File file=new File(filepath);
            File zipFile=new File(zippath);

            input=new FileInputStream(file);
            zipOut=new ZipOutputStream(new FileOutputStream(zipFile));
            zipOut.putNextEntry(new ZipEntry(file.getName()));

            int tmp=0;
            byte[] buffer=new byte[1024];
            while((tmp=input.read(buffer,0,1024))!=-1){
                zipOut.write(buffer,0,tmp);
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            try{
                input.close();
                zipOut.close();

            }catch (Exception ex){
                ex.printStackTrace();
            }
        }
    }

(二)、压缩一个文件夹(包含多个文件)

 public static void main(String[] args) {
        //文件夹路径
        String filepath="D:\\markavip\\";
        //压缩后的文件夹路径
        String zippath="D:\\markTest.zip";
        zipDirFile(filepath,zippath);
    }

    public static void zipDirFile(String filepath,String zippath){
        try{
            File file=new File(filepath);
            File zipFile=new File(zippath);

            InputStream input=null;
            ZipOutputStream zipOut=new ZipOutputStream(new FileOutputStream(zipFile));

            if(file.isDirectory()){
                File[]  files=file.listFiles();
                for(int i=0;i<files.length;i++){
                    input=new FileInputStream(files[i]);
                    zipOut.putNextEntry(new ZipEntry(file.getName()+File.separator+files[i].getName()));
                    int tmp=0;
                    byte[] buf=new byte[1024];
                    while((tmp=input.read(buf,0,1024))!=-1){
                        zipOut.write(buf,0,tmp);
                    }
                    input.close();
                }
            }else{
                //调用单个压缩文件
                    ZipOneFile.zipFile(filepath,zippath);
            }
            zipOut.close();

        }catch (Exception e){
            e.printStackTrace();
        }
    }

(三)解压单个文件

public static void main(String[] args) {
        //压缩的文件路径
        String zippath="D:\\markavip\\test.zip";
        //解压之后的文件路径
        String outfilepath="D:\\markavip\\one.txt";
        //压缩文件中的文件名
        String filename="测试.txt";
        zipContraFile(zippath,outfilepath,filename);
    }
    public static void  zipContraFile(String zippath,String outfilepath,String filename){
        try{
            File file=new File(zippath);
            File outFile=new File(outfilepath);
            ZipFile zipFile=new ZipFile(file);
            ZipEntry entry=zipFile.getEntry(filename);
            InputStream input=zipFile.getInputStream(entry);
            OutputStream output=new FileOutputStream(outFile);
            int tmp=0;
            byte[] buf=new byte[1024];
            while((tmp=input.read(buf,0,1024))!=-1){
                output.write(buf,0,tmp);
            }
            input.close();
            output.close();
        }catch (Exception e){
            e.printStackTrace();
        }finally {

        }
    }

(四)、解压一个文件夹(内含多个文件)

 public static void main(String[] args) {
        //压缩文件路径
        String zippath="D:\\markTest.zip";
        //解压后的路径
        String outfilepath="D:\\YOHO";
        zipContraMultiFile(zippath,outfilepath);
    }

    public static void zipContraMultiFile(String zippath,String outfilepath ){
        ZipInputStream zipInput=null;
        ZipFile zipFile=null;
        InputStream input=null;
        OutputStream output=null;
        try{
            File file=new File(zippath);
            File outFile=null;

            zipFile=new ZipFile(file);
            zipInput=new ZipInputStream(new FileInputStream(file));

            ZipEntry entry=null;
            while ((entry=zipInput.getNextEntry())!=null){
                outFile=new File(outfilepath+File.separator+entry.getName());
                if(!outFile.getParentFile().exists()){
                    outFile.getParentFile().mkdir();
                }
                if(!outFile.exists()){
                    outFile.createNewFile();
                }
                input=zipFile.getInputStream(entry);
                output=new FileOutputStream(outFile);
                int tmp=0;
                byte[] buf=new byte[1024];
                while((tmp=input.read(buf,0,1024))!=-1){
                    output.write(buf,0,tmp);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try{
                input.close();
                output.close();
                zipInput.close();
                zipFile.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }

    }

参考文章:
http://www.2cto.com/kf/201412/363662.html
http://www.cnblogs.com/chiangfai/p/5888141.html
http://blog.youkuaiyun.com/u011423071/article/details/52043702

### 异常原因 `java.lang.IllegalArgumentException: MALFORMED` 异常通常在处理 ZIP 文件时,因文件路径名包含非法字符或不符合标准编码格式而引发。`ZipCoder.toString` 方法在将字节序列转换为字符串时,若遇到无法正确解码的字节序列,就会抛出此异常。 常见原因如下: - **编码不兼容**:ZIP 文件中的文件名采用的编码与 Java 运行环境默认编码不一致,导致解码失败。 - **非法字符**:文件名包含操作系统或 ZIP 规范不允许的非法字符。 - **文件损坏**:ZIP 文件本身损坏,致使文件名信息不完整或错误。 ### 解决办法 #### 1. 指定编码 可以在创建 `ZipInputStream` 时,指定正确的编码格式,以确保文件名能正确解码。示例代码如下: ```java import java.io.FileInputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; public class ZipFileProcessing { public static void main(String[] args) { try (ZipInputStream zis = new ZipInputStream(new FileInputStream("example.zip"), java.nio.charset.Charset.forName("GBK"))) { ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { System.out.println(entry.getName()); zis.closeEntry(); } } catch (IOException e) { e.printStackTrace(); } } } ``` 在上述代码中,通过 `java.nio.charset.Charset.forName("GBK")` 指定使用 GBK 编码来处理 ZIP 文件中的文件名。 #### 2. 检查并清理文件名 在处理 ZIP 文件之前,检查文件名是否包含非法字符,并进行清理。示例代码如下: ```java import java.io.FileInputStream; import java.io.IOException; import java.util.regex.Pattern; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; public class ZipFileProcessing { private static final Pattern ILLEGAL_CHAR_PATTERN = Pattern.compile("[\\\\/:*?\"<>|]"); public static void main(String[] args) { try (ZipInputStream zis = new ZipInputStream(new FileInputStream("example.zip"))) { ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { String cleanName = ILLEGAL_CHAR_PATTERN.matcher(entry.getName()).replaceAll("_"); System.out.println(cleanName); zis.closeEntry(); } } catch (IOException e) { e.printStackTrace(); } } } ``` 在上述代码中,使用正则表达式 `[\\\\/:*?\"<>|]` 匹配非法字符,并将其替换为下划线。 #### 3. 检查文件完整性 使用文件校验工具(如 MD5、SHA-1 等)检查 ZIP 文件的完整性,确保文件未损坏。若文件损坏,尝试重新下载或获取正确的 ZIP 文件。 ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值