我正在尝试开发可以处理具有非英文字符(变音符号,阿拉伯语等)的压缩文件的代码,但压缩文件包含不正确的名称.我使用的是java版本1.7.0_45因此它不应该是由于这里提到的错误.我正在为ZipOutputStream
构造函数将字符集设置为UTF-8,并且按照Javadocs它应该按照我的要求工作.
我确信zip文件正在正确写入,因为尝试从文件中读取条目会提供正确的文件名(如预期的那样).
但是,当我尝试使用Ubuntu默认的ArchiveManager/Unzip工具打开/解压缩时,文件名会混乱.
这是我的代码:
private void convertFilesToZip(Listfiles) { FileInputStream inputStream = null; try { byte[] buffer = new byte[1024]; FileOutputStream fileOutputStream = new FileOutputStream("zipFile.zip"); ZipOutputStream outputStream = new ZipOutputStream(fileOutputStream, Charset.forName("UTF-8")); for (File file : files) { inputStream = new FileInputStream(file); String filename = file.getName(); System.out.println("Adding file : " + filename); outputStream.putNextEntry(new ZipEntry(filename)); int length; while ((length = inputStream.read(buffer)) > 0) { outputStream.write(buffer, 0, length); } outputStream.closeEntry(); } if(inputStream != null) inputStream.close(); outputStream.close(); System.out.println("Zip created successfully"); System.out.println("======================================================="); System.out.println("Reading zip Entries"); ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(new File("zipFile.zip")), Charset.forName("UTF-8")); ZipEntry zipEntry; while((zipEntry=zipInputStream.getNextEntry())!=null){ System.out.println(zipEntry.getName()); zipInputStream.closeEntry(); } zipInputStream.close(); } catch (IOException exception) { exception.printStackTrace(); } }
文件的输出如下:
Adding file : umlaut_?.txt Adding file : ? ? ? ? ? ? ?.txt Adding file : ä?c??ös? ???Ÿ_uploadFile4.txt Adding file : pingüino.txt Adding file : ÄÖÜäöüß- Español deEspaña.ppt Zip created successfully ======================================================= Reading zip Entries umlaut_?.txt ? ? ? ? ? ? ?.txt ä?c??ös? ???Ÿ_uploadFile4.txt pingüino.txt ÄÖÜäöüß- Español deEspaña.ppt
有没有人成功实现了我希望在这里实现的目标.有人能指出我可能错过的或者做错了.我做了所有的谷歌,我甚至尝试Apache Commons Compress
但仍然没有运气.
它在bug报告中提到在Java 7中解决了bug,那么为什么代码不能正常工作.
任何帮助都非常感谢.提前致谢.