import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; 改为 import org.apache.tools.zip.ZipEntry; import org.apache.tools.zip.ZipOutputStream;
ant包里提供ZipOutputStream类的setEncoding("gbk")方法。
zos.setEncoding("gbk");
下载地址如下:
https://mvnrepository.com/artifact/org.apache.ant/ant/1.7.1 (点击进入页面,本页面被覆盖)
package file; import java.io.BufferedInputStream; import java.io.bufferedoutputstream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import org.apache.tools.zip.ZipEntry; import org.apache.tools.zip.ZipOutputStream; public class Zip { public static void main(String[] args) { //文件所在路径 String path = "E:\\test"; File dir = new File(path); if(!dir.isDirectory()) { System.out.println(path + "--路径不存在!"); } //所有文件 File[] files = new File(path).listFiles(); if(files == null || files.length < 1) { System.out.println(path + "--路径下无文件!"); } //压缩文件名 String zipname = "hello.zip"; File zipFile = new File(path + File.separator + zipname); if(zipFiles(files,zipFile) == 0) { System.out.println("压缩文件ok!"); } } public static int zipFiles(File[] files,File zipFile) { if (zipFile.exists()) { System.out.println(zipFile + "--压缩文件已存在!"); return -1; } BufferedInputStream bis = null; ZipOutputStream zos = null; try { zos = new ZipOutputStream(new bufferedoutputstream(new FileOutputStream(zipFile))); byte[] bufs = new byte[1024*10]; for(int i=0;i<files.length;i++){ //创建ZIP实体,并添加进压缩包 ZipEntry zipEntry = new ZipEntry(files[i].getName()); zos.putNextEntry(zipEntry); //乱码问题 zos.setEncoding("gbk"); bis = new BufferedInputStream(new FileInputStream(files[i]),1024*10); int read = 0; while((read=bis.read(bufs,1024*10)) != -1){ zos.write(bufs,0,read); } } return 0; }catch (IOException e) { e.printstacktrace(); System.out.println("压缩文件过程BUG了!"); return -1; } finally { try { if (zos != null) { zos.close(); } } catch (Exception e) { e.printstacktrace(); } try { if (bis != null) { bis.close(); } } catch (Exception e) { e.printstacktrace(); } } } }