Java (ZipEntry) - if the file name contains czech characters (čžř etc) it fails while reading next entry

StackOverflow https://stackoverflow.com/questions/17424606

Question

I have a problem when I try to unzip file contains files with special characters.

Lets say I have a zip file gallery.zip with image files.

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

My method starts:

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) {

It fails in inputStream.getNextEntry() when I try to read file dařbuján.jpg because of czech letters "ř" and "á". It works well with the other files for example with spaces (104 25.jpg or simply file.jpg etc.). Can you help me please?

Was it helpful?

Solution 2

Ok, I solved it with commons-compress. If somebody is interested here is my method:

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

OTHER TIPS

Create your ZipInputStream with Charset specified using

 ZipInputStream(InputStream in, Charset charset)

like

new ZipInputStream(inputStream, Charset.forName("UTF-8"));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top