zip打包乱码问题
转载于 http://blog.sina.com.cn/s/blog_4b6f8d150100kyzc.html
由于项目里需要做一个将文件夹压缩的功能,由于文件夹中的文件都是中文名称,所以java.util.zip压缩后的文件名都是变成了“乱码”。
解决方法有二:
其一,修改源码
参考 http://nopainnogain.javaeye.com/blog/616436
其二,用ant.jar包里面的org.apache.tools.zip代替java.util.zip
import org.apache.tools.zip.ZipEntry; import org.apache.tools.zip.ZipOutputStream; public static void write(File path, File zipFile) throws IOException { ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(zipFile)); zip.setEncoding("GBK"); //这行代码就是解决中文文件名的关键 Util.write(path, path, zip); zip.close(); } private static void write(File base, File path, ZipOutputStream zip) throws IOException { URI rel = base.toURI().relativize(path.toURI()); if (path.isDirectory()) { ZipEntry entry = new ZipEntry(rel.getPath()); entry.setUnixMode(755); zip.putNextEntry(entry); zip.closeEntry(); File[] files = path.listFiles(); for (File file : files) { write(base, file, zip); } } else { ZipEntry entry = new ZipEntry(rel.getPath()); entry.setUnixMode(644); zip.putNextEntry(entry); FileInputStream is = new FileInputStream(path); zip.write(IOUtils.toByteArray(is)); is.close(); zip.closeEntry(); } }
public void setUnixMode(int mode) { // CheckStyle:MagicNumberCheck OFF - no point setExternalAttributes((mode << 16) // MS-DOS read-only attribute | ((mode & 0200) == 0 ? 1 : 0) // MS-DOS directory flag | (isDirectory() ? 0x10 : 0)); // CheckStyle:MagicNumberCheck ON platform = PLATFORM_UNIX; }