如何使用UTF-8编码打开java程序生成的zip文件

时间:2011-06-07 09:21:43

标签: java encoding zip unzip 7zip

我们的产品有一个导出功能,它使用ZipOutputStream压缩目录;但是,当您尝试压缩包含具有中文或日文字符的文件名的目录时,导出将无法正常工作。由于某种原因,压缩文件中的新文件的命名方式不同。以下是我们的压缩代码示例:

ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName));
out.setEncoding("UTF-8");
//program to add directory to zip 
//program add/create file to zip
out.close();

我的导入算法也是用Java构建的,可以正确导入压缩文件,即使它在文件/目录名中包含中文/日文字符。

 Zipfile zipfile = new ZipFile(zipPath, "UTF-8");
 Enumeration e = zipFile.getEntries();
 while (e.hasMoreElements()) {
 entry = (ZipEntry) e.nextElement();
 String name = entry.getName();
         ....

zip软件的程序是否在解压缩UTF-8编码文件时遇到问题,或者是否有一些特殊需要创建一个zip文件,现有软件可以使用utf-8编码轻松使用?


我写了一个示例程序:

package ZipFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;

public class ZipFolder{
public static void main(String[] a) throws Exception
{
String srcFolder = "D:/9.4_work/openscript_repo/中文124.All/中文";
String destZipFile = "D:/Eclipse_Projects/OpenScriptDebuggingProject/src/ZipFile/demo.zip";
zipFolder(srcFolder, destZipFile);
}

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

    fileWriter = new FileOutputStream(destZipFile);
    zip = new ZipOutputStream(fileWriter);
    zip.setEncoding("UTF-8");
    // using GBK encoding, the chinese name can be correctly displayed when unzip
    // zip.setEncoding("GBK");

    addFolderToZip("", 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
{
    File folder = new File(srcFolder);

    for (String fileName : folder.list()) {
        if (path.equals("")) {
            addFileToZip(folder.getName(), srcFolder + "/" + fileName, zip);
        }
        else {
            addFileToZip(path + "/" + folder.getName(), srcFolder + "/" + fileName, zip);
        }
    }
}

}

2 个答案:

答案 0 :(得分:1)

这里的最佳答案可以回答你的问题;不幸的是,它似乎表明Zip格式并不真正允许创建一个Zip文件,可以在任何计算机上正确显示文件名:

https://superuser.com/questions/60379/linux-zip-tgz-filenames-encoding-problem

我希望它在你将编码设置为GBK时有效,因为这是你系统的默认编码,所以7zip正在使用它来打开它所有的zip文件。

它表明rar7z格式有更好的支持。

我在Java的拉链中找到了一篇专门介绍UTF-8的博客文章。它表明有一个较新版本的ZIP规范,当前版本的Java可能没有创建,但Java 7会这样做。我不知道Apache类是否也使用它。

http://blogs.oracle.com/xuemingshen/entry/non_utf_8_encoding_in

答案 1 :(得分:1)

以下实用程序类允许您使用GZIP压缩算法压缩和解压缩字符串。例如,如果要在数据库中保存长字符串,这可能很有用。

import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
import java.util.zip.GZIPOutputStream;
import java.util.zip.GZIPInputStream;


public class GzipStringUtil {


    public static byte[] compressString(String uncompressedString) throws IllegalArgumentException, IllegalStateException {
        if (uncompressedString == null) {
            throw new IllegalArgumentException("The uncompressed string specified was null.");
        }
        try {
            byte[] utfEncodedBytes = uncompressedString.getBytes("UTF-8");
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            GZIPOutputStream gzipOutputStream = new GZIPOutputStream(baos);
            gzipOutputStream.write(utfEncodedBytes);
            gzipOutputStream.finish();
            gzipOutputStream.close();
            return baos.toByteArray();
        }
        catch (Exception e) {
            throw new IllegalStateException("GZIP compression failed: " + e, e);
        }
    }


    public static String uncompressString(byte[] compressedString) throws IllegalArgumentException, IllegalStateException {
        if (compressedString == null) {
            throw new IllegalArgumentException("The compressed string specified was null.");
        }
        try {
            ByteArrayInputStream bais = new ByteArrayInputStream(compressedString);
            GZIPInputStream gzipInputStream = new GZIPInputStream(bais);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            for (int value = 0; value != -1;) {
                value = gzipInputStream.read();
                if (value != -1) {
                    baos.write(value);
                }
            }
            gzipInputStream.close();
            baos.close();
            return new String(baos.toByteArray(), "UTF-8");
        }
        catch (Exception e) {
            throw new IllegalStateException("GZIP uncompression failed: " + e, e);
        }
    }
}

这是一个TestCase,它提供了上面类的示例用法:

public class GzipStringUtilTest extends TestCase {

    public void testGzipStringUtil() {
        String input = "This is a test. This is a test. This is a test. This is a test. This is a test.";
        System.out.println("Input:        [" + input + "]");
        byte[] compressed = GzipStringUtil.compressString(input);
        System.out.println("Compressed:   " + Arrays.toString(compressed));
        System.out.println("-> Compressed input string of length " + input.length() + " to " + compressed.length + " bytes");
        String uncompressed = GzipStringUtil.uncompressString(compressed);
        System.out.println("Uncompressed: [" + uncompressed + "]");
        assertEquals("The uncompressed string [" + uncompressed + "] unexpectedly does not match the input string [" + input + "]", input, uncompressed);
        System.out.println("The input was compressed and uncompressed successfully, and the input matches uncompressed output.");
    }
}