Go ZIP压缩文件读写操作

创建zip文件

golang提供了**archive/zip**包来处理zip压缩文件,下面通过一个简单的示例来展示golang如何创建zip压缩文件:

Go 复制代码
func createZip(filename string) {
	// 缓存压缩文件内容
	buf := new(bytes.Buffer)
 
	// 创建zip
	writer := zip.NewWriter(buf)
	defer writer.Close()
 
	// 读取文件内容
	content, _ := ioutil.ReadFile(filepath.Clean(filename))
 
	// 接收
	f, _ := writer.Create(filename)
	f.Write(content)
 
	filename = strings.TrimSuffix(filename, path.Ext(filename)) + ".zip"
	ioutil.WriteFile(filename, buf.Bytes(), 0644)
}

读取zip文件

读取zip文档过程与创建zip文档过程类似,需要解压后的文档目录结构创建:

Go 复制代码
func readZip(filename string) {
      zipFile, err := zip.OpenReader(filename)
		if err != nil {
			panic(err.Error())
		}
		defer zipFile.Close()
 
		for _, f := range zipFile.File {
			info := f.FileInfo()
			if info.IsDir() {
				err = os.MkdirAll(f.Name, os.ModePerm)
				if err != nil {
					panic(err.Error())
				}
				continue
			}
			srcFile, err := f.Open()
			if err != nil {
				panic(err.Error())
			}
			defer srcFile.Close()
 
			newFile, err := os.Create( f.Name)
			if err != nil {
				panic(err.Error())
			}
			defer newFile.Close()
 
			io.Copy(newFile, srcFile)
		}
}
相关推荐
郝学胜-神的一滴15 分钟前
【技术实战】500G单行大文件读取难题破解!生成器+自定义函数最优方案解析
开发语言·python·程序人生·面试
愤豆19 分钟前
02-Java语言核心-语法特性-注解体系详解
java·开发语言·python
晴栀ay34 分钟前
Generator + RxJS 重构 LLM 流式输出的“丝滑”架构
javascript·后端·llm
是翔仔呐35 分钟前
第13章 SPI通信协议全解:底层时序、4种工作模式与W25Qxx Flash芯片读写实战
c语言·开发语言·stm32·单片机·嵌入式硬件·学习·gitee
下次一定x37 分钟前
深度解析 Kratos 客户端服务发现与负载均衡:从 Dial 入口到 gRPC 全链路落地(下篇)
后端·go
2401_8785302142 分钟前
自定义内存布局控制
开发语言·c++·算法
wjs20241 小时前
SQLite 子查询
开发语言
AndrewMe82111 小时前
detailed-docx:一个能保住格式的 Word 文档操作库
开发语言·python·word
IT方大同1 小时前
RT_thread(RTOS实时操作系统)线程的创建与切换
c语言·开发语言·嵌入式硬件
智算菩萨1 小时前
【OpenGL】6 真实感光照渲染实战:Phong模型、材质系统与PBR基础
开发语言·python·游戏引擎·游戏程序·pygame·材质·opengl