简体   繁体   中英

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

I have a zip file with the following content:

在此处输入图片说明

The content inside Temperature_°C.log : unit°C

and i use the following code to print all the file names inside a 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);
        }
    }

and at line : ZipEntry zipEntry = entries.nextElement(); for the Temperature_°C.log it throws java.lang.IllegalArgumentException: MALFORMED

I tried UTF-8 and it is not working. When i tried with ISO-8859-1 it displays junk character.

How should i solve this ?

Got the same problem, but with cyrillic characters. Had to use commons-compress library instead of standard.

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM