Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add zip entry with utf-8 name to zip

Tags:

java

zip

I have a method which adds inputStream to zip as an entry:

private void addToZip(InputStream is, String filename) throws Exception {
    try {
        ZipEntry zipEntry = new ZipEntry(filename);
        zos.putNextEntry(zipEntry);
        byte[] bytes = new byte[1024];
        int length;
        while ((length = is.read(bytes)) >= 0) {
            zos.write(bytes, 0, length);
        }
        zos.closeEntry();
    } finally {
        IOUtils.closeQuietly(is);
    }
}

The problem occurs when the filename contains an UTF-8 char like áé... In zip file it will be saved as ????? and when I unzip it in ubuntu 12.10 it looks like: N├бstroje instead of Nástroje.

For this example I used jdk6 but now I've also tried jdk7:

zos = new ZipOutputStream(fos, Charset.forName("UTF-8"));

But with no success.

I also tried Apache Commons Zip and set encoding but also with no success.

So how I can add this file with unicode symbols in filename to zip ?

like image 758
hudi Avatar asked Mar 20 '13 09:03

hudi


2 Answers

seems this line solved my problem:

        zos.setCreateUnicodeExtraFields(UnicodeExtraFieldPolicy.ALWAYS);

can someone explain me what is this doing and why it works ?

like image 55
hudi Avatar answered Nov 17 '22 16:11

hudi


Zip archive by default uses DOS(OEM) codepage to store filenames. Linux/unix implementations uses system codepage when unpacking. Mac OS uses utf-8 by default. So in your case filename is stored correctly, but Linux archiver doesn't understand it.

like image 35
Nickolay Olshevsky Avatar answered Nov 17 '22 17:11

Nickolay Olshevsky