简体   繁体   中英

ZipEntry UTF-8 charset

I'm creating some zip files inside a main zip (name finalZip.zip) using Java, and these filenames has characters like áóç. When I try to create a zip file, the name of the file is wrong. For example, when 3-ORDINÁRIA-2017-05-03.zip, it comes 3-ORDIN+üRIA-2017-05-03.zip

String zipName= number + "- ORDINÁRIA -" + sdf.format(sdfComplete.parse(date.getTime()) + ".zip";

ByteArrayOutputStream bos = new ByteArrayOutputStream();
ZipOutputStream zip = new ZipOutputStream(bos);
try {
  bos = createZipFile(); // populate each zipFile with some images
  // generating zip file, ex: 6-ORDINÁRIA-2017-03-15.zip
  zipFinal.putNextEntry(new ZipEntry(zipName));
  zipFinal.write(bos.toByteArray());
  zipFinal.closeEntry();
}

...

I want the zip files with UTF-8 charset. How can I solve this charset problem?

Use the public ZipOutputStream(OutputStream out, Charset charset) constructor to specify the charset for both the entry names and comments.

The method's javadoc :

Creates a new ZIP output stream.

Parameters:

out the actual output stream

charset the charset to be used to encode the entry names and comments

For example this uses the UTF-8 charset :

ZipOutputStream zip = new ZipOutputStream(bos, java.nio.charset.StandardCharsets.UTF_8);

In case someone still has that problem or the data into the file cannot be utf-8

  • First the invoque method must be like these:
    final ZipOutputStream zip = new ZipOutputStream(baos, java.nio.charset.StandardCharsets.UTF_8);

  • When insert data and it cant be encoded:
    zip.write(data.toString().getBytes("UTF-8"));

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