纯粹为了记录。
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* 压缩成ZIP 方法1
* @param srcDir 压缩文件夹路径
* @param out 压缩文件输出流
* @param KeepDirStructure 是否保留原来的目录结构,true:保留目录结构;
* false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
* @throws RuntimeException 压缩失败会抛出运行时异常
*/
public static void toZip(String srcDir, OutputStream out, boolean KeepDirStructure)
throws RuntimeException{
long start = System.currentTimeMillis();
ZipOutputStream zos = null ;
try {
zos = new ZipOutputStream(out);
File sourceFile = new File(srcDir);
compress(sourceFile,zos,sourceFile.getName(),KeepDirStructure);
long end = System.currentTimeMillis();
System.out.println("压缩完成,耗时:" + (end - start) +" ms");
} catch (Exception e) {
throw new RuntimeException("zip error from ZipUtils",e);
}finally{
if(zos != null){
try {
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 压缩成ZIP 方法2
* @param srcFiles 需要压缩的文件列表
* @param out 压缩文件输出流
* @throws RuntimeException 压缩失败会抛出运行时异常
*/
public static void toZip(List<File> srcFiles , OutputStream out)throws RuntimeException {
long start = System.currentTimeMillis();
ZipOutputStream zos = null ;
try {
zos = new ZipOutputStream(out);
for (File srcFile : srcFiles) {
byte[] buf = new byte[BUFFER_SIZE];
zos.putNextEntry(new ZipEntry(srcFile.getName()));
int len;
FileInputStream in = new FileInputStream(srcFile);
while ((len = in.read(buf)) != -1){
zos.write(buf, 0, len);
}
zos.closeEntry();
in.close();
}
long end = System.currentTimeMillis();
System.out.println("压缩完成,耗时:" + (end - start) +" ms");
} catch (Exception e) {
throw new RuntimeException("zip error from ZipUtils",e);
}finally{
if(zos != null){
try {
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 递归压缩方法
* @param sourceFile 源文件
* @param zos zip输出流
* @param name 压缩后的名称
* @param KeepDirStructure 是否保留原来的目录结构,true:保留目录结构;
* false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
* @throws Exception
*/
private static void compress(File sourceFile, ZipOutputStream zos, String name,
boolean KeepDirStructure) throws Exception{
byte[] buf = new byte[BUFFER_SIZE];
if(sourceFile.isFile()){
// 向zip输出流中添加一个zip实体,构造器中name为zip实体的文件的名字
zos.putNextEntry(new ZipEntry(name));
// copy文件到zip输出流中
int len;
FileInputStream in = new FileInputStream(sourceFile);
while ((len = in.read(buf)) != -1){
zos.write(buf, 0, len);
}
// Complete the entry
zos.closeEntry();
in.close();
} else {
File[] listFiles = sourceFile.listFiles();
if(listFiles == null || listFiles.length == 0){
// 需要保留原来的文件结构时,需要对空文件夹进行处理
if(KeepDirStructure){
// 空文件夹的处理
zos.putNextEntry(new ZipEntry(name + "/"));
// 没有文件,不需要文件的copy
zos.closeEntry();
}
}else {
for (File file : listFiles) {
// 判断是否需要保留原来的文件结构
if (KeepDirStructure) {
// 注意:file.getName()前面需要带上父文件夹的名字加一斜杠,
// 不然最后压缩包中就不能保留原来的文件结构,即:所有文件都跑到压缩包根目录下了
compress(file, zos, name + "/" + file.getName(),KeepDirStructure);
} else {
compress(file, zos, file.getName(),KeepDirStructure);
}
}
}
}
}
FileOutputStream fos1 = new FileOutputStream(new File("D:\\study\\博士\\雷达数据\\test\\test.zip"));
toZip("D:/study/博士/雷达数据/test/test", fos1,true);
C#版本
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System;
using System.Data;
using System.Configuration;
using System.Collections.Generic;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Checksums;
namespace RadarData
{
/// <summary>
/// 文件(夹)压缩、解压缩
/// </summary>
public class FileCompression
{
#region 压缩文件
/// <summary>
/// 压缩文件
/// </summary>
/// <param name="fileNames">要打包的文件列表</param>
/// <param name="GzipFileName">目标文件名</param>
/// <param name="CompressionLevel">压缩品质级别(0~9)</param>
/// <param name="deleteFile">是否删除原文件</param>
public static void CompressFile(List<FileInfo> fileNames, string GzipFileName, int CompressionLevel, bool deleteFile)
{
ZipOutputStream s = new ZipOutputStream(File.Create(GzipFileName));
try
{
s.SetLevel(CompressionLevel); //0 - store only to 9 - means best compression
foreach (FileInfo file in fileNames)
{
FileStream fs = null;
try
{
fs = file.Open(FileMode.Open, FileAccess.ReadWrite);
}
catch
{ continue; }
// 方法二,将文件分批读入缓冲区
byte[] data = new byte[2048];
int size = 2048;
ZipEntry entry = new ZipEntry(Path.GetFileName(file.Name));
entry.DateTime = (file.CreationTime > file.LastWriteTime ? file.LastWriteTime : file.CreationTime);
s.PutNextEntry(entry);
while (true)
{
size = fs.Read(data, 0, size);
if (size <= 0) break;
s.Write(data, 0, size);
}
fs.Close();
if (deleteFile)
{
file.Delete();
}
}
}
finally
{
s.Finish();
s.Close();
}
}
/// <summary>
/// 压缩文件夹
/// </summary>
/// <param name="dirPath">要打包的文件夹</param>
/// <param name="GzipFileName">目标文件名</param>
/// <param name="CompressionLevel">压缩品质级别(0~9)</param>
/// <param name="deleteDir">是否删除原文件夹</param>
public static void CompressDirectory(string dirPath, string GzipFileName, int CompressionLevel, bool deleteDir)
{
//压缩文件为空时默认与压缩文件夹同一级目录
if (GzipFileName == string.Empty)
{
GzipFileName = dirPath.Substring(dirPath.LastIndexOf("//") + 1);
GzipFileName = dirPath.Substring(0, dirPath.LastIndexOf("//")) + "//" + GzipFileName + ".zip";
}
//if (Path.GetExtension(GzipFileName) != ".zip")
//{
// GzipFileName = GzipFileName + ".zip";
//}
using (ZipOutputStream zipoutputstream = new ZipOutputStream(File.Create(GzipFileName)))
{
zipoutputstream.SetLevel(CompressionLevel);
Crc32 crc = new Crc32();
Dictionary<string, DateTime> fileList = GetAllFies(dirPath);
foreach (KeyValuePair<string, DateTime> item in fileList)
{
FileStream fs = File.OpenRead(item.Key.ToString());
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
ZipEntry entry = new ZipEntry(item.Key.Substring(dirPath.Length));
entry.DateTime = item.Value;
entry.Size = fs.Length;
fs.Close();
crc.Reset();
crc.Update(buffer);
entry.Crc = crc.Value;
zipoutputstream.PutNextEntry(entry);
zipoutputstream.Write(buffer, 0, buffer.Length);
}
}
if (deleteDir)
{
Directory.Delete(dirPath, true);
}
}
/// <summary>
/// 获取所有文件
/// </summary>
/// <returns></returns>
private static Dictionary<string, DateTime> GetAllFies(string dir)
{
Dictionary<string, DateTime> FilesList = new Dictionary<string, DateTime>();
DirectoryInfo fileDire = new DirectoryInfo(dir);
if (!fileDire.Exists)
{
throw new System.IO.FileNotFoundException("目录:" + fileDire.FullName + "没有找到!");
}
GetAllDirFiles(fileDire, FilesList);
GetAllDirsFiles(fileDire.GetDirectories(), FilesList);
return FilesList;
}
/// <summary>
/// 获取一个文件夹下的所有文件夹里的文件
/// </summary>
/// <param name="dirs"></param>
/// <param name="filesList"></param>
private static void GetAllDirsFiles(DirectoryInfo[] dirs, Dictionary<string, DateTime> filesList)
{
foreach (DirectoryInfo dir in dirs)
{
foreach (FileInfo file in dir.GetFiles("*.*"))
{
filesList.Add(file.FullName, file.LastWriteTime);
}
GetAllDirsFiles(dir.GetDirectories(), filesList);
}
}
/// <summary>
/// 获取一个文件夹下的文件
/// </summary>
/// <param name="dir">目录名称</param>
/// <param name="filesList">文件列表HastTable</param>
private static void GetAllDirFiles(DirectoryInfo dir, Dictionary<string, DateTime> filesList)
{
foreach (FileInfo file in dir.GetFiles("*.*"))
{
filesList.Add(file.FullName, file.LastWriteTime);
}
}
#endregion
#region 解压缩文件
/// <summary>
/// 解压缩文件
/// </summary>
/// <param name="GzipFile">压缩包文件名</param>
/// <param name="targetPath">解压缩目标路径</param>
public static void Decompress(string GzipFile, string targetPath)
{
//string directoryName = Path.GetDirectoryName(targetPath + "//") + "//";
string directoryName = targetPath;
if (!Directory.Exists(directoryName)) Directory.CreateDirectory(directoryName);//生成解压目录
string CurrentDirectory = directoryName;
byte[] data = new byte[2048];
int size = 2048;
ZipEntry theEntry = null;
using (ZipInputStream s = new ZipInputStream(File.OpenRead(GzipFile)))
{
while ((theEntry = s.GetNextEntry()) != null)
{
if (theEntry.IsDirectory)
{// 该结点是目录
if (!Directory.Exists(CurrentDirectory + theEntry.Name)) Directory.CreateDirectory(CurrentDirectory + theEntry.Name);
}
else
{
if (theEntry.Name != String.Empty)
{
// 检查多级目录是否存在
if (theEntry.Name.Contains("//"))
{
string parentDirPath = theEntry.Name.Remove(theEntry.Name.LastIndexOf("//") + 1);
if (!Directory.Exists(parentDirPath))
{
Directory.CreateDirectory(CurrentDirectory + parentDirPath);
}
}
//解压文件到指定的目录
using (FileStream streamWriter = File.Create(CurrentDirectory + theEntry.Name))
{
while (true)
{
size = s.Read(data, 0, data.Length);
if (size <= 0) break;
streamWriter.Write(data, 0, size);
}
streamWriter.Close();
}
}
}
}
s.Close();
}
}
#endregion
}
}
lib包下载地址:http://pan.baidu.com/s/1pLausnL