当前位置:网站首页>Read and write of zip file
Read and write of zip file
2022-07-26 07:54:00 【I like iced black tea】
Zip File reading
ZipInputStream The basic usage of :
First, create a ZipInputStream, It's usually an incoming FileInputStream As a data source , And then the loop calls getNextEntry(), When the return value is null when , Express zip End of stream reading .
One ZipEntry Represents a compressed file or directory , If it's a compressed file , We will use read() Method to read , When the return value is -1 when , End of read .
Code implementation
public class Main {
public static void main(String[] args) {
try (ZipInputStream in = new ZipInputStream(new FileInputStream("C:\\IO flow \\Test.zip"),Charset.forName("gbk"))) {
ZipEntry entry = null;
// Extract each sub file in the compressed file
while((entry = in.getNextEntry())!=null) {
System.out.println(entry.getName());
int data = -1;
while((data = in.read())!= -1){
System.out.println(data);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
So let's use ZipInputStream Input stream , Realize a decompression function by yourself
Function realization : To a zip Unzip the file
Implementation steps :1, Create the decompression directory , obtain zip The name of the document , according to zip File name , Extract the name of the compressed Directory , Create the decompression directory , Then create the directory .
2, Traverse and read Zip Each sub file in the file , Create a buffered output stream , take Zip The file bytes read in the file are written into the new file , It should be noted that : Every time you create an output stream , We all need to turn it off manually , When fewer file bytes are written , There will be buffer bytes that cannot be written normally .
public class Main {
public static void main(String[] args) {
// To decompress zip file
File zipFile = new File("C:\\IO flow \\Test.zip");
//1. Create the decompression directory
// obtain zip The name of the document
String zipFileName = zipFile.getName();
// according to zip File name , Extract the name of the compressed Directory
String targetFileName = zipFileName.substring(0,zipFileName.indexOf("."));
// Create the decompression directory
File targetDir = new File(zipFile.getParent() + "\\" + targetFileName);
if(!targetDir.exists()) {
targetDir.mkdir();// Create directory
}
//2. Parse read zip file
try (
ZipInputStream in = new ZipInputStream(new FileInputStream(zipFile),Charset.forName("gbk"))) {
// Traverse Zip Each sub file in the file
ZipEntry zipEntry = null;
while((zipEntry = in.getNextEntry())!=null) {
// obtain zip The name of the sub file in the compressed package
String zipEntryFileName = zipEntry.getName();
// Create the output stream of this file
String zipFilePath = targetDir.getPath() + "\\" + zipEntryFileName;
// The output stream is defined in try() block , End automatic buffer emptying and close
try(BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(zipFilePath))){ ;
// Read the byte contents of the sub file
byte[] buff = new byte[1024];
int len = -1;
while ((len = in.read(buff)) != -1) {
bos.write(buff, 0, len);
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Zip Writing files
ZipOutputStream It's a kind of FilterOutputStream, It can write content directly to zip package . We need to create one first ZipOutputStream, Usually a package FileOutStream, then , Before writing a file , First call putNextEntry( ), And then use write() write in byte[ ] data , Call after completion closeEntry( ), End the packaging of this file .
Let's take advantage of ZipOutputStream The output stream implements the specified function : Write the specified file zip file
Function realization : Compress a file directory .
Implementation steps :1, Get and traverse the list of sub files in the original directory .
2, The byte contents of the original file , write in zip Compressed package .
We're doing zip When the file is written , It should be noted that the zip The compressed package should be under the same parent directory as the original directory .
public class Main {
public static void main(String[] args) {
// Original directory
File rootDir = new File("C:\\IO flow \\Test");
// The files in the original directory , write in zip Compressed files
try ( ZipOutputStream out = new ZipOutputStream(new FileOutputStream(rootDir.getParent()+"\\"+rootDir.getName()+".zip"))) {
// Get and traverse the list of sub files in the original directory
File[] files = rootDir.listFiles();
for (File file : files) {
// Create a ZipEntry
out.putNextEntry(new ZipEntry(file.getName()));
// The byte contents of the original file , write in zip Compressed package
out.write(Files.readAllBytes(file.toPath()));
// End the present ZipEntry
out.closeEntry();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
边栏推荐
猜你喜欢

Audio and video learning (10) -- PS streaming

Web page basic label

Installation of Baidu flying paste deep learning framework tutorial in Anaconda
![[classic thesis of recommendation system (10)] Alibaba SDM model](/img/a5/3ae37b847042ffb34e436720f61d17.png)
[classic thesis of recommendation system (10)] Alibaba SDM model

【每日一题】919. 完全二叉树插入器

MySQL之执行计划

Program environment and pretreatment

程序环境和预处理

时间序列分析预测实战之ARIMA模型

WCF deployed on IIS
随机推荐
元宇宙基础设施:WEB 3.0 chain33 优势分析
数据库基础
QT listview add controls and pictures
Leetcode 206. reverse chain list (2022.07.25)
Summary of distributed related interview questions
Idea settings set shortcut keys to convert English letters to case in strings
Model pruning 3: learning structured sparsity in deep neural networks
为啥谷歌的内部工具不适合你?
1. MySQL Architecture [MySQL advanced]
机器学习相关比赛网站
在线问题反馈模块实战(十四):实现在线答疑功能
OVS underlying implementation principle
Hcip--- MPLS detailed explanation and BGP route filtering
DADNN: Multi-Scene CTR Prediction via Domain-Aware Deep Neural Network
Unity Metaverse(二)、Mixamo & Animator 混合树与动画融合
Anaconda 中安装 百度飞浆Paddle 深度学习框架 教程
Come across the sea to see you
Logical volume management (LVM)
Leetcode sword finger offer special (I) integer
分布式相关面试题总结