关于ZIP压缩问题 解决中文文件名乱码

本文介绍了一个使用Apache工具实现的ZIP压缩与解压缩的类,提供了压缩、解压缩、递归压缩等功能,并详细解释了如何通过Apache Zip API进行文件的压缩与解压缩操作,包括使用ZipOutputStream与ZipInputStream进行文件的读写,以及如何处理中文路径等问题。

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

用ant.jar进行ZIP压缩

这是一个类:
package com.zipup;
import java.io.BufferedInputStream;  
import java.io.BufferedOutputStream;  
import java.io.File;  
import java.io.FileInputStream;  
import java.io.FileNotFoundException;  
import java.io.FileOutputStream;  
import java.io.IOException;  
import java.util.Enumeration;  
import java.util.zip.CRC32;  
import java.util.zip.CheckedInputStream;  
import java.util.zip.CheckedOutputStream;  
import java.util.zip.Deflater;  
import java.util.zip.ZipException;  
import java.util.zip.ZipInputStream;  
import org.apache.tools.zip.ZipEntry;  
import org.apache.tools.zip.ZipFile;  
import org.apache.tools.zip.ZipOutputStream;  
  
import android.util.Log;  
/** 
*  
* [一句话功能简述]<BR> 
* [功能详细描述] 
* @author zhouxin 
* @version [Android MTVClient C01, 2011-3-4] 
*/  
public class ZipControl  
{  
    private static boolean isCreateSrcDir = false;//是否创建源目录 在这里的话需要说明下。如果需要创建源目录的话。就在这里设为true否则为false;   
    private static String TAG="ZipControl";  
    /** 
     *  
     * [对指定路径下文件的压缩处理]<BR> 
     * [功能详细描述] 
     *  
     * @param src 径地址 
     * @param archive 指定到压缩文件夹的路径 
     * @param comment 描述 
     * @throws FileNotFoundException 文件没有找到异常 
     * @throws IOException IO输入异常 
     */  
    public  void writeByApacheZipOutputStream(String[] src,  
        String archive, String comment) throws FileNotFoundException,  
        IOException  
    {  
        Log.e(TAG, "writeByApacheZipOutputStream");  
        //----压缩文件:   
        FileOutputStream f = new FileOutputStream(archive);  
        //使用指定校验和创建输出流   
        CheckedOutputStream csum = new CheckedOutputStream(f, new CRC32());  
        ZipOutputStream zos = new ZipOutputStream(csum);  
        //支持中文   
        zos.setEncoding("GBK");  
        BufferedOutputStream out = new BufferedOutputStream(zos);  
        //设置压缩包注释   
        zos.setComment(comment);  
        //启用压缩   
        zos.setMethod(ZipOutputStream.STORED);  
        //压缩级别为最强压缩,但时间要花得多一点   
        zos.setLevel(Deflater.BEST_COMPRESSION);  
        // 如果为单个文件的压缩在这里修改   
        for (int i = 0; i < src.length; i++)  
        {  
            Log.e(TAG, "src["+i+"] is "+src);  
            File srcFile = new File(src);  
            if (!srcFile.exists()  
                || (srcFile.isDirectory() && srcFile.list().length == 0))  
            {  
                Log.e(TAG, "!srcFile.exists()");  
                throw new FileNotFoundException(  
                    "File must exist and ZIP file must have at least one entry.");  
            }  
            String strSrcString = src;  
            //获取压缩源所在父目录   
            strSrcString = strSrcString.replaceAll("////", "/");  
            String prefixDir = null;  
            if (srcFile.isFile())  
            {  
                prefixDir = strSrcString.substring(0, strSrcString  
                    .lastIndexOf("/") + 1);  
            }  
            else  
            {  
                prefixDir = (strSrcString.replaceAll("/$", "") + "/");  
            }  
            //如果不是根目录   
            if (prefixDir.indexOf("/") != (prefixDir.length() - 1)  
                && isCreateSrcDir)  
            {  
                prefixDir = prefixDir.replaceAll("[^/]+/$", "");  
            }  
            //开始压缩   
            writeRecursive(zos, out, srcFile, prefixDir);  
        }  
  
        out.close();  
        // 注:校验和要在流关闭后才准备,一定要放在流被关闭后使用   
        Log.e(TAG, "Checksum: " + csum.getChecksum().getValue());  
        @SuppressWarnings("unused")  
        BufferedInputStream bi;  
    }  
    /** 
     *  
     * [* 使用 org.apache.tools.zip.ZipFile 解压文件,它与 java 类库中的 
     * java.util.zip.ZipFile 使用方式是一新的,只不过多了设置编码方式的 接口。 
     *  
     * 注,apache 没有提供 ZipInputStream 类,所以只能使用它提供的ZipFile 来读取压缩文件。]<BR> 
     *  
     * @param archive 压缩包路径 
     * @param decompressDir 解压路径 
     * @throws IOException 
     * @throws FileNotFoundException 
     * @throws ZipException 
     */  
  
    @SuppressWarnings("unchecked")  
    public static void readByApacheZipFile(String archive, String decompressDir)  
        throws IOException, FileNotFoundException, ZipException  
    {  
        Log.e(TAG, "readByApacheZipFile");  
        BufferedInputStream bi;  
        ZipFile zf = new ZipFile(archive, "GBK");//支持中文   
        Enumeration e = zf.getEntries();  
        while (e.hasMoreElements())  
        {  
            ZipEntry ze2 = (ZipEntry) e.nextElement();  
            String entryName = ze2.getName();  
            String path = decompressDir + "/" + entryName;  
            if (ze2.isDirectory())  
            {  
                Log.e(TAG, "正在创建解压目录 - " + entryName);  
                File decompressDirFile = new File(path);  
                if (!decompressDirFile.exists())  
                {  
                    decompressDirFile.mkdirs();  
                }  
            }  
            else  
            {  
                Log.e(TAG, "正在创建解压文件 - " + entryName);  
                String fileDir = path.substring(0, path.lastIndexOf("/"));  
                File fileDirFile = new File(fileDir);  
                if (!fileDirFile.exists())  
                {  
                    fileDirFile.mkdirs();  
                }  
                BufferedOutputStream bos = new BufferedOutputStream(  
                    new FileOutputStream(decompressDir + "/" + entryName));  
                bi = new BufferedInputStream(zf.getInputStream(ze2));  
                byte[] readContent = new byte[1024];  
                int readCount = bi.read(readContent);  
                while (readCount != -1)  
                {  
                    bos.write(readContent, 0, readCount);  
                    readCount = bi.read(readContent);  
                }  
                bos.close();  
            }  
        }  
        zf.close();  
    }  
    /** 
     *  
     * [使用 java api 中的 ZipInputStream 类解压文件,但如果压缩时采用了 
     * org.apache.tools.zip.ZipOutputStream时,而不是 java 类库中的 
     * java.util.zip.ZipOutputStream时,该方法不能使用,原因就是编码方 式不一致导致,运行时会抛如下异常: 
     * java.lang.IllegalArgumentException at 
     * java.util.zip.ZipInputStream.getUTF8String(ZipInputStream.java:290) 
     *  
     * 当然,如果压缩包使用的是java类库的java.util.zip.ZipOutputStream 压缩而成是不会有问题的,但它不支持中文 ]<BR> 
     * [功能详细描述] 
     *  
     * @param archive 压缩包路径 
     * @param decompressDir 解压路径 
     * @throws FileNotFoundException 
     * @throws IOException 
     */  
    public static void readByZipInputStream(String archive, String decompressDir)  
        throws FileNotFoundException, IOException  
    {  
        BufferedInputStream bi;  
        //----解压文件(ZIP文件的解压缩实质上就是从输入流中读取数据):   
        Log.e(TAG, "开始读压缩文件");  
        FileInputStream fi = new FileInputStream(archive);  
        CheckedInputStream csumi = new CheckedInputStream(fi, new CRC32());  
        ZipInputStream in2 = new ZipInputStream(csumi);  
        bi = new BufferedInputStream(in2);  
        java.util.zip.ZipEntry ze;//压缩文件条目   
        //遍历压缩包中的文件条目   
        while ((ze = in2.getNextEntry()) != null)  
        {  
            String entryName = ze.getName();  
            if (ze.isDirectory())  
            {  
                Log.e(TAG,"正在创建解压目录 - " + entryName);  
                File decompressDirFile = new File(decompressDir + "/"  
                    + entryName);  
                if (!decompressDirFile.exists())  
                {  
                    decompressDirFile.mkdirs();  
                }  
            }  
            else  
            {  
                Log.e(TAG, "正在创建解压文件 - " + entryName);  
                BufferedOutputStream bos = new BufferedOutputStream(  
                    new FileOutputStream(decompressDir  
                        + "/"  
                        + entryName.substring(entryName.lastIndexOf("//"),  
                            entryName.length()  
                                - (entryName.lastIndexOf("//") - 2))));  
                byte[] buffer = new byte[1024];  
                int readCount = bi.read(buffer);  
                while (readCount != -1)  
                {  
                    bos.write(buffer, 0, readCount);  
                    readCount = bi.read(buffer);  
                }  
                bos.close();  
            }  
        }  
        bi.close();  
        Log.e(TAG, "Checksum: " + csumi.getChecksum().getValue());  
    }  
  
    /** 
     *  
     * [递归压缩 
     *  
     * 使用 org.apache.tools.zip.ZipOutputStream 类进行压缩,它的好处就是支持中文路径, 而Java类库中的 
     * java.util.zip.ZipOutputStream 压缩中文文件名时压缩包会出现乱码。 使用 apache 中的这个类与 java 
     * 类库中的用法是一新的,只是能设置编码方式了。]<BR> 
     * [功能详细描述] 
     *  
     * @param zos 
     * @param bo 
     * @param srcFile 
     * @param prefixDir 
     * @throws IOException 
     * @throws FileNotFoundException 
     */  
    private static void writeRecursive(ZipOutputStream zos,  
        BufferedOutputStream bo, File srcFile, String prefixDir)  
        throws IOException, FileNotFoundException  
    {  
        Log.e(TAG, "writeRecursive");  
        ZipEntry zipEntry;  
        String filePath = srcFile.getAbsolutePath().replaceAll("////", "/")  
            .replaceAll("//", "/");  
        if (srcFile.isDirectory())  
        {  
            filePath = filePath.replaceAll("/$", "") + "/";  
        }  
        String entryName = filePath.replace(prefixDir, "").replaceAll("/$", "");  
        if (srcFile.isDirectory())  
        {  
            if (!"".equals(entryName))  
            {  
                Log.e(TAG, "正在创建目录 - " + srcFile.getAbsolutePath()  
                    + " entryName=" + entryName);  
                //如果是目录,则需要在写目录后面加上 /   
                zipEntry = new ZipEntry(entryName + "/");  
                zos.putNextEntry(zipEntry);  
            }  
            File srcFiles[] = srcFile.listFiles();  
            for (int i = 0; i < srcFiles.length; i++)  
            {  
                writeRecursive(zos, bo, srcFiles, prefixDir);  
            }  
        }  
        else  
        {  
            Log.e(TAG,"正在写文件 - " + srcFile.getAbsolutePath()  
                + " entryName=" + entryName );  
            BufferedInputStream bi = new BufferedInputStream(  
                new FileInputStream(srcFile));  
            //开始写入新的ZIP文件条目并将流定位到条目数据的开始处   
            zipEntry = new ZipEntry(entryName);  
            zos.putNextEntry(zipEntry);  
            byte[] buffer = new byte[1024];  
            int readCount = bi.read(buffer);  
            while (readCount != -1)  
            {  
                bo.write(buffer, 0, readCount);  
                readCount = bi.read(buffer);  
            }  
            //注,在使用缓冲流写压缩文件时,一个条件完后一定要刷新一把,不   
            //然可能有的内容就会存入到后面条目中去了   
            bo.flush();  
            //文件读完后关闭   
            bi.close();  
        }  
    }  

}  



问题出错在这:
setMethod(int method) 设置条目的压缩方法,可以为 ZipOutputStream.STORED 或 ZipOutputStream .DEFLATED。
我把zos.setMethod(ZipOutputStream.DEFLATED);//设置成ZipOutputStream .DEFLATED 可以正常压缩
可是把  zos.setMethod(ZipOutputStream.STORED); //设置成ZipOutputStream .STORED 不能压缩了

提示错误
java.util.zip.ZipException: uncompressed size is required for STORED method when not writing to a file// 
压缩的大小所需的存储方法时,不写入文件
at org.apache.tools.zip.ZipOutputStream.putNextEntry(ZipOutputStream.java:418)
如何解决 帮帮忙
package com.cliff.common; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Enumeration; import org.apache.tools.zip.ZipEntry; import org.apache.tools.zip.ZipFile; import org.apache.tools.zip.ZipOutputStream; /** * * 类名: ZipUtil.java * 描述:压缩/解压缩zip包处理类 * 创建者:XXX * 创建日期:2015年5月7日 - 下午1:35:02 * 版本: V0.1 * 修改者: * 修改日期: */ public class ZipUtil { /** * * 功能描述:压缩文件 * 创建者:XXX * 创建日期: 2015年5月7日 - 下午1:35:18 * 版本: V0.1 * 修改者: * 修改日期: * @param directory 指定压缩文件路径 压缩到同目录 * @throws IOException * void */ public static void zip(String directory) throws FileNotFoundException, IOException { zip("", null, directory); } /** * * 功能描述:压缩文件 * 创建者:XXX * 创建日期: 2015年5月7日 - 下午1:36:03 * 版本: V0.1 * 修改者: * 修改日期: * @param zipFileName 压缩产生的zip文件名--带路径,如果为null或空则默认按文件名生产压缩文件名 * @param relativePath 相对路径,默认为空 * @param directory 文件或目录的绝对路径 * void */ public static void zip(String zipFileName, String relativePath, String directory) throws FileNotFoundException, IOException { String fileName = zipFileName; if (fileName == null || fileName.trim().equals("")) { File temp = new File(directory); if (temp.isDirectory()) { fileName = directory + ".zip"; } else { if (directory.indexOf(".") > 0) { fileName = directory.substring(0, directory.lastIndexOf("."))+ "zip"; } else { fileName = directory + ".zip"; } } } ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(fileName)); try { zip(zos, relativePath, directory); } catch (IOException ex) { throw ex; } finally { if (null != zos) { zos.close(); } } } /** * * 功能描述:压缩文件 * 创建者:XXX * 创建日期: 2015年5月7日 - 下午1:37:55 * 版本: V0.1 * 修改者: * 修改日期: * @param zos 压缩输出流 * @param relativePath 相对路径 * @param absolutPath 文件或文件夹绝对路径 * @throws IOException * void */ private static void zip(ZipOutputStream zos, String relativePath, String absolutPath) throws IOException { File file = new File(absolutPath); if (file.isDirectory()) { File[] files = file.listFiles(); for (int i = 0; i < files.length; i++) { File tempFile = files[i]; if (tempFile.isDirectory()) { String newRelativePath = relativePath + tempFile.getName() + File.separator; createZipNode(zos, newRelativePath); zip(zos, newRelativePath, tempFile.getPath()); } else { zipFile(zos, tempFile, relativePath); } } } else { zipFile(zos, file, relativePath); } } /** * * 功能描述:压缩文件 * 创建者:XXX * 创建日期: 2015年5月7日 - 下午1:38:46 * 版本: V0.1 * 修改者: * 修改日期: * @param zos 压缩输出流 * @param file 文件对象 * @param relativePath 相对路径 * @throws IOException * void */ private static void zipFile(ZipOutputStream zos, File file, String relativePath) throws IOException { ZipEntry entry = new ZipEntry(relativePath + file.getName()); zos.putNextEntry(entry); InputStream is = null; try { is = new FileInputStream(file); int BUFFERSIZE = 2 <= 0) { zos.write(buffer, 0, length); } zos.flush(); zos.closeEntry(); } catch (IOException ex) { throw ex; } finally { if (null != is) { is.close(); } } } /** * * 功能描述:创建目录 * 创建者:XXX * 创建日期: 2015年5月7日 - 下午1:39:12 * 版本: V0.1 * 修改者: * 修改日期: * @param zos zip输出流 * @param relativePath 相对路径 * @throws IOException * void */ private static void createZipNode(ZipOutputStream zos, String relativePath) throws IOException { ZipEntry zipEntry = new ZipEntry(relativePath); zos.putNextEntry(zipEntry); zos.closeEntry(); } /** * * 功能描述:解压缩文件 * 创建者:XXX * 创建日期: 2015年5月7日 - 下午1:39:32 * 版本: V0.1 * 修改者: * 修改日期: * @param zipFilePath zip文件路径 * @param targetPath 解压缩到的位置,如果为null或空字符串则默认解压缩到跟zip包同目录跟zip包同名的文件夹下 * void */ public static void unzip(String zipFilePath, String targetPath) throws IOException { InputStream is = null; FileOutputStream fileOut = null; File file = null; ZipFile zipFile = null; try { zipFile = new ZipFile(zipFilePath,"GBK"); String directoryPath = ""; if (null == targetPath || "".equals(targetPath)) { directoryPath = zipFilePath.substring(0, zipFilePath.lastIndexOf(".")); } else { directoryPath = targetPath; } for(Enumeration entries = zipFile.getEntries(); entries.hasMoreElements();){ ZipEntry entry = (ZipEntry)entries.nextElement(); file = new File(directoryPath+"/"+entry.getName()); if(entry.isDirectory()){ file.mkdirs(); }else{ //如果指定文件的目录不存在,则创建之. File parent = file.getParentFile(); if(!parent.exists()){ parent.mkdirs(); } is = zipFile.getInputStream(entry); fileOut = new FileOutputStream(file); int readLen = 0; byte[] buffer = new byte[4096]; while ((readLen = is.read(buffer, 0, 4096)) >= 0) { fileOut.write(buffer, 0, readLen); } fileOut.close(); is.close(); } } zipFile.close(); } catch (IOException ex) { throw ex; } finally { if(null != zipFile){ zipFile = null; } if (null != is) { is.close(); } if (null != fileOut) { fileOut.close(); } } } /** * * 功能描述:生产文件 如果文件所在路径不存在则生成路径 * 创建者:XXX * 创建日期: 2015年5月7日 - 下午1:41:04 * 版本: V0.1 * 修改者: * 修改日期: * @param fileName 文件名 带路径 * @param isDirectory 是否为路径 * @return * File */ public static File buildFile(String fileName, boolean isDirectory) { File target = new File(fileName); if (isDirectory){ target.mkdirs(); } else { if (!target.getParentFile().exists()) { target.getParentFile().mkdirs(); target = new File(target.getAbsolutePath()); } } return target; } }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值