Java : Read a file with special characters from a Zip file

标签 java character-encoding zip

我有一个包含以下内容的 zip 文件:

enter image description here

Temperature_°C.log里面的内容:unit°C

我使用以下代码打印 zip 中的所有文件名:

public static void main(String[] args) {
        try {
            ZipFile zipFile = new ZipFile("Test.zip", Charset.forName("UTF-8"));

            Enumeration<? extends ZipEntry> entries = zipFile.entries();
            while (entries.hasMoreElements()) {
                try {
                    ZipEntry zipEntry = entries.nextElement();
                    System.out.println(zipEntry.getName());

                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                }
            }
            zipFile.close();
        } catch (IOException ex) {
            Logger.getLogger(ZipTest.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

在行:ZipEntry zipEntry = entries.nextElement(); Temperature_°C.log 它抛出 java.lang.IllegalArgumentException: MALFORMED

我试过 UTF-8 但它不工作。当我尝试使用 ISO-8859-1 时,它显示垃圾字符。

我该如何解决?

最佳答案

有同样的问题,但有西里尔字符。必须使用 commons-compress库而不是标准。

import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipFile;


public static void main(String[] args) {
    try(ZipFile zipFile = new ZipFile("Test.zip")) { //UTF-8 by default
        Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();
        while (entries.hasMoreElements()) {
            try {
                ZipArchiveEntry zipEntry = entries.nextElement();
                System.out.println(zipEntry.getName());
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            }
        }
    } catch (IOException ex) {
        Logger.getLogger(ZipTest.class.getName()).log(Level.SEVERE, null, ex);
    }
}

关于Java : Read a file with special characters from a Zip file,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64448616/

相关文章:

c# - 创建并流式传输图像存档 zip 文件以供下载 C#

java - 当 2 个 xsd 文件中有 2 个 XmlRootElement 时,编码/解码

utf-8 - 如何创建名称中包含非打印字符的文件?

iphone - 如何使用 iCloud 在我的应用程序之间同步 .zip 文件?

python - 尝试使用 chardet 猜测文件的编码

windows - 如何在 Windows 批处理文件中使用多种颜色?

c++ - (C++) 解压缩 0 字节的文件时出现错误 ZR_FLATE。解压源: "Zip Utils -clean, elegant...."

java - 检查字符串是否为有效数字的逻辑

java - 在 Android 上更改 Google map 中的标记

java - Keycloak 管理客户端响应 Bad Request 以尝试列出领域