Java(ZipEntry) - 如果文件名包含捷克字符(čžřetc),则在读取下一个条目时失败

时间:2013-07-02 11:38:29

标签: java inputstream zipfile zipinputstream

当我尝试解压缩包含特殊字符的文件时出现问题。

假设我有一个包含图像文件的zip文件gallery.zip。

gallery.zip
  - file01.jpg
  - dařbuján.jpg

我的方法开始了:

public List<File> unzipToTemporaryFolder(ZipInputStream inputStream)
        throws IOException {
    List<File> files = new LinkedList<File>();
    ZipEntry entry = null;
    int count;
    byte[] buffer = new byte[BUFFER];

    while ((entry = inputStream.getNextEntry()) != null) {

当我尝试读取文件dařbuján.jpg时,由于捷克字母“ř”和“á”,它在inputStream.getNextEntry()中失败。它适用于其他文件,例如空格(104 25.jpg或简单的file.jpg等)。你能帮帮我吗?

2 个答案:

答案 0 :(得分:2)

使用

指定 Charset 创建 ZipInputStream
 ZipInputStream(InputStream in, Charset charset)

new ZipInputStream(inputStream, Charset.forName("UTF-8"));

答案 1 :(得分:1)

好的,我用commons-compress解决了它。如果有人对此感兴趣,请使用我的方法:

public List<File> unzipToTemporaryFolder(ZipInputStream inputStream,
        File tempFile) throws IOException {
    List<File> files = new LinkedList<File>();
    int count;
    byte[] buffer = new byte[BUFFER];

    org.apache.commons.compress.archivers.zip.ZipFile zf = new org.apache.commons.compress.archivers.zip.ZipFile(tempFile, "UTF-8");
    Enumeration<?> entires = zf.getEntries();
    while(entires.hasMoreElements()) {
        org.apache.commons.compress.archivers.zip.ZipArchiveEntry entry = (org.apache.commons.compress.archivers.zip.ZipArchiveEntry)entires.nextElement();
        if(entry.isDirectory()) {
            unzipDirectoryZipEntry(files, entry);
        } else {            
            InputStream zin = zf.getInputStream(entry);                 

            File temp = File.createTempFile(entry.getName().substring(0, entry.getName().length() - 4) + "-", "." + entry.getName().substring(entry.getName().length() - 3, entry.getName().length()));                                     

            OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(temp), BUFFER);
            while ((count = zin.read(buffer, 0, BUFFER)) != -1) {
                outputStream.write(buffer, 0, count);
            }
            outputStream.flush();
            zin.close();
            outputStream.close();
            files.add(temp);            
        }
    }
    zf.close();
    return files;
}