代码可直接使用
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
// zip方式压缩和解压缩,操作单个文件
public class ResZipUtil {
// 缓冲区大小
public static final int BUFFER = 1024;
/**
* 压缩,单个文件
*
* @param source, eg:c:\\A_886_2017122001_0001.txt
* @param target, eg:c:\\A_886_2017122001_0001.zip
*/
public static void zipFile(String source, String target) throws IOException {
InputStream input = null;
ZipOutputStream zipOutput = null;
try {
File file = new File(source); // 定义要压缩的文件
input = new FileInputStream(file); // 定义文件的输入流
File targetFile = new File(target); // 定义压缩文件名称
zipOutput = new ZipOutputStream(new FileOutputStream(targetFile));
zipOutput.putNextEntry(new ZipEntry(file.getName())); // 设置ZipEntry对象
byte[] buf = new byte[BUFFER];
int length = 0;
while ((length = input.read(buf)) != -1) { // 读取内容
zipOutput.write(buf, 0, length); // 压缩输出
}
} finally {
if (input != null) {
input.close(); // 关闭输入流
}
if (zipOutput != null) {
zipOutput.close(); // 关闭输出流
}
}
}
/**
* 解压,单个文件,并返回解压后的文件名
*
* @param source, eg:c:\\A_886_2017122001_0001.zip
* @param target, eg:c:\\A_886_2017122001_0001.txt
*
* @return, eg:A_886_2017122001_0001.txt
*/
public static String unZipFile(String source, String target) throws IOException {
ZipFile zipFile = null;
InputStream input = null;
OutputStream out = null;
String filename = null;
try {
File file = new File(source); // 找到压缩文件
zipFile = new ZipFile(file); // 实例化ZipFile对象
ZipEntry zipEntry = (ZipEntry) zipFile.entries().nextElement(); // 得到一个压缩实体
input = zipFile.getInputStream(zipEntry); // 得到一个压缩实体的输入流
filename = zipEntry.getName(); //返回值所用
File targetFile = new File(target); // 定义解压缩的文件名称
out = new FileOutputStream(targetFile); // 实例化输出流
byte[] buf = new byte[BUFFER];
int length = 0;
while ((length = input.read(buf)) != -1) {
out.write(buf, 0, length);
}
} finally { //防止程序抛异常也能关闭
if (zipFile != null) {
zipFile.close();
}
if (input != null) {
input.close(); // 关闭输入流
}
if (out != null) {
out.close(); // 关闭输出流
}
}
return filename;
}
}