import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class Test {
/**
* 缓冲区大小
*/
protected static final int BUFFER = 8192;
/**
* 压缩文件夹,并把压缩包存放在与该文件夹统计的目录下,压缩包名称为: 文件夹名称 + “.zip”
*
* @param directory 要压缩的文件夹
* @param destDir 压缩包存放的文件夹路径
* @param fileName 压缩包名称
* @return File 压缩包文件
* @throws Exception
*/
public static File zipFile(String directory, String destDir, String fileName) throws Exception {
File dir = new File(directory);
if(!dir.exists())
return null;
String zipFileName = destDir;
if(!zipFileName.endsWith("\\")){
zipFileName += "\\";
}
if(!fileName.endsWith("zip")) {
zipFileName += fileName + ".zip";
}
else {
zipFileName += fileName;
}
File zipFile = new File(zipFileName);
FileOutputStream fileOS = null;
ZipOutputStream zipOut = null;
try{
fileOS = new FileOutputStream(zipFile);
zipOut = new ZipOutputStream(fileOS);
String baseDir = "";
zip(dir, zipOut, baseDir);
}
catch(FileNotFoundException e){
zipFile = null;
throw e;
}
catch(Exception e){
zipFile = null;
e.printStackTrace();
throw e;
}
finally{
try{
if(zipOut != null) {
zipOut.close();
}
}
catch(IOException e){
e.printStackTrace();
}
}
return zipFile;
}
/**
* 压缩文件
*
* @param file 要压缩的文件
* @param zipOut 输出流
* @param baseDir 压缩包里的起始文件夹,压缩的文件都放在这个文件夹下
* @throws Exception
*/
public static void zip(File file, ZipOutputStream zipOut, String baseDir) throws Exception{
if(!file.exists())
return;
//判断是目录还是文件
if(file.isDirectory()){
zipDirectory(file, zipOut, baseDir);
}
else{
zipSingleFile(file, zipOut, baseDir);
}
}
/**
* 压缩目录
*/
public static void zipDirectory(File dir, ZipOutputStream zipOut, String baseDir)throws Exception{
if(!dir.exists()) {
return;
}
File[] files = dir.listFiles();
for(File file : files){
//递归
zip(file, zipOut, baseDir + dir.getName() + "\\");
}
}
/**
* 压缩一个具体文件
*
* @param file 文件
* @param zipOut
* @param baseDir void
*/
public static void zipSingleFile(File file, ZipOutputStream zipOut, String baseDir) throws Exception{
if(!file.exists()) {
return;
}
BufferedInputStream bis = null;
try{
bis = new BufferedInputStream(new FileInputStream(file));
ZipEntry entry = new ZipEntry(baseDir + file.getName());
zipOut.putNextEntry(entry);
int count = 0;
byte[] data = new byte[BUFFER];
while(count != -1){
count = bis.read(data, 0, BUFFER);
if(count != -1) {
zipOut.write(data, 0, count);
}
}
}
finally{
try{
if(bis != null) {
bis.close();
}
}
catch(IOException e){
e.printStackTrace();
}
}
}
public static void main(String[] args) {
try {
// 注意这里的E:\\test1需事先存在
zipFile("E:\\test", "E:\\test1", "testZip");
} catch (Exception e) {
e.printStackTrace();
}
}
}
java压缩文件夹
最新推荐文章于 2023-05-25 09:03:36 发布