PS:下面main方法有演示;
1,导入jar
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant</artifactId>
<version>1.9.4</version>
</dependency>
如果你不是maven,那么下载
[ ant.jar包下载]
2,示例代码
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.CRC32;
import java.util.zip.CheckedOutputStream;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
public class FileCompress {
static final int BUFFER = 8192;
private File zipFile;
public FileCompress(String pathName) {
zipFile = new File(pathName);
}
/**
* 压缩文件
* @param srcPathName
*/
public void compress(String srcPathName) {
File file = new File(srcPathName);
if (!file.exists()){
throw new RuntimeException(srcPathName + "不存在!");
}
try {
FileOutputStream fileOutputStream = new FileOutputStream(zipFile);
CheckedOutputStream cos = new CheckedOutputStream(fileOutputStream,
new CRC32());
ZipOutputStream out = new ZipOutputStream(cos);
out.setEncoding("gbk");
String basedir = "";
compress(file, out, basedir);
out.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 压缩一个目录
* @param dir
* @param out
* @param basedir
*/
private void compressDirectory(File dir, ZipOutputStream out, String basedir) {
if (!dir.exists())return;
File[] files = dir.listFiles();
for (int i = 0; i < files.length; i++) {
compress(files[i], out, basedir + dir.getName() + "/");
}
}
private void compress(File file, ZipOutputStream out, String basedir) {
if (file.isDirectory()) {
this.compressDirectory(file, out, basedir);
} else {
this.compressFile(file, out, basedir);
}
}
/**
* 压缩一个文件
* @param file
* @param out
* @param basedir
*/
private void compressFile(File file, ZipOutputStream out, String basedir) {
if (!file.exists()) {
return;
}
try {
BufferedInputStream bis = new BufferedInputStream(
new FileInputStream(file));
ZipEntry entry = new ZipEntry(basedir + file.getName());
out.putNextEntry(entry);
int count;
byte data[] = new byte[BUFFER];
while ((count = bis.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
}
bis.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
FileCompress zc = new FileCompress("H://中文.zip");
zc.compress("H://test中文");
System.out.println("123");
}
}
![这里写图片描述](https://img-blog.csdn.net/20170822100057716?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcXFfMzU4NjAwOTc=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)