纯粹为了记录。

参考了

https://www.cnblogs.com/zeng1994/p/7862288.html

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#版本

https://www.cnblogs.com/hahahayang/p/hahahayang.html

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[];
int size = ;
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, , size);
if (size <= ) break;
s.Write(data, , 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("//") + );
GzipFileName = dirPath.Substring(, 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, , 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, , 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[];
int size = ;
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("//") + );
if (!Directory.Exists(parentDirPath))
{
Directory.CreateDirectory(CurrentDirectory + parentDirPath);
}
} //解压文件到指定的目录
using (FileStream streamWriter = File.Create(CurrentDirectory + theEntry.Name))
{
while (true)
{
size = s.Read(data, , data.Length);
if (size <= ) break;
streamWriter.Write(data, , size);
}
streamWriter.Close();
}
}
}
}
s.Close();
}
}
#endregion
}
}

lib包下载地址:http://pan.baidu.com/s/1pLausnL

Java /C# 实现文件压缩的更多相关文章

  1. Java 多个文件压缩下载

    有时候会有多个附件一起下载的需求,这个时候最好就是打包下载了 首先下面这段代码是正常的单个下载 public void Download(@RequestParam("file_path&q ...

  2. java实现将文件压缩成zip格式

    以下是将文件压缩成zip格式的工具类(复制后可以直接使用): zip4j.jar包下载地址:http://www.lingala.net/zip4j/download.php package util ...

  3. 利用Java进行zip文件压缩与解压缩

    摘自: https://www.cnblogs.com/alphajuns/p/12442315.html 工具类: package com.alphajuns.util; import java.i ...

  4. Java实现多文件压缩打包的方法

    package com.biao.test; import java.io.File; import java.io.FileInputStream; import java.io.FileOutpu ...

  5. java多个文件压缩下载

    public static void zipFiles(File[] srcfile,ServletOutputStream sos){ byte[] buf=new byte[1024]; try ...

  6. Java实现文件压缩与解压

    Java实现ZIP的解压与压缩功能基本都是使用了Java的多肽和递归技术,可以对单个文件和任意级联文件夹进行压缩和解压,对于一些初学者来说是个很不错的实例.(转载自http://www.puiedu. ...

  7. [Java 基础] 使用java.util.zip包压缩和解压缩文件

    reference :  http://www.open-open.com/lib/view/open1381641653833.html Java API中的import java.util.zip ...

  8. Java I/O 文件加锁,压缩

    文件加锁: 文件加锁机制允许我们同步访问某个作为共享资源的文件. public class Test { public static void main(String[] args) throws I ...

  9. Java实现文件压缩与解压[zip格式,gzip格式]

    Java实现ZIP的解压与压缩功能基本都是使用了Java的多肽和递归技术,可以对单个文件和任意级联文件夹进行压缩和解压,对于一些初学者来说是个很不错的实例. zip扮演着归档和压缩两个角色:gzip并 ...

随机推荐

  1. 关于PL/SQL Developer与Oracle客户端

    这是一个很简单的知识点,但这些年遇到过太多初学者反而受其困扰,所以还是决定记录一下. 背景:国内使用Oracle的群体,几乎都会使用PL/SQL Developer这个图形化的工具进行日常数据维护.这 ...

  2. Spring Boot:快速入门

    上一篇讲述什么是Spring Boot,这一篇讲解怎么使用IDE工具快速搭建起来独立项目. 一.构建方式 快速搭建项目有三种方式,官方也有答案给到我们: 二.构建前准备 想要使用IDE运行起来自己的S ...

  3. linux配制DNS服务器基本能功能

    1.环境 Centos 6.5 bind 关闭防火墙和SELINUX 2.安装bind服务软件 yum -y install bind 3.配制主配制文件/etc/name.conf options ...

  4. RNA-seq workflow

    SRAtoolkit download .fa http://www.genomicdataanalysis.com/genomicdatatype/rna-seq/

  5. 使用Redux DevTools浏览器插件调试redux

    与redux的Devtools模块不同,该工具主要依赖浏览器插件完成.模式也比Devtools简单点. step1 下载插件 Chrome地址(360极速模式也可以用): https://chrome ...

  6. IT题库3-线程实现的方式

    1.继承Thread类创建线程 Thread类本质上是实现了Runnable接口的一个实例,代表一个线程的实例.启动线程的唯一方法就是通过Thread类的start()实例方法.start()方法是一 ...

  7. (简单)华为M3揽月 BTV-W09的Usb调试模式在哪里开启的经验

    每次我们使用pc链上安卓手机的时候,如果手机没有开启Usb调试模式,pc则没办法成功识别我们的手机,有时候,我们使用的一些功能较好的app如以前我们使用的一个app引号精灵,老版本就需要开启Usb调试 ...

  8. .NET平台常用的开发组件(csdn)

    .NET平台常用的开发组件 原创 2017年02月24日 09:20:04 工欲善其事,必先利其器.学习.NET也10年有余,其优雅的编程风格,高效率的开发速度,极度简单的可扩展性,足够强大开发类库, ...

  9. 使用laraval框架和前端完成restful风格的请求对接(这里只是讨论restful的概念)

    现在,在开发中restful风格的api是比较流行的,尤其是在前后端分离的架构中. 这些东西这一下这篇文章中说的很详细:RESTful接口设计原则和优点 下面,我们来讨论如何使用laraval和前端完 ...

  10. SOAR SQL进行优化和改写的自动化工具

    前言 SQL优化是程序开发中经常遇到的问题,尤其是在程序规模不断扩大的时候.SQL的好坏不仅制约着程序的规模,影响着用户的体验,甚至威胁着信息的安全. 我们经常听到说哪家平台挂了,哪家网站被黑了,但我 ...