前言

如何用Java对文件进行加压和压缩

上篇文章说了项目中对根据URL提供的HTML代码中的文件URL进行下载,将下载后的文件存放在服务器上,但是文件下载下来都是ZIP压缩包。那么这篇就来看Java如何多文件进行解压缩操作。

一、正文

这里没有使用其他的jar包,利用Java中的IO流直接对文件进行操作,为了方便将文件放入桌面,路径为:C:\Users\Surpass\Desktop

二、使用步骤

博主尽量在代码中添加明确的注释,以便于理解,所以直接贴代码了。

1.单文件压缩

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/**
* @author Surpass
* @Package com.hkrt.demo.zip
* @Description: 单文件压缩
* @date 2020/10/16 10:51
*/
public class SingleZipCompression {

private static InputStream inputStream;
private static ZipOutputStream zipOutputStream;
private static OutputStream outputStream;
private static String filePath = "C:\\Users\\Surpass\\Desktop\\Linux就该这么学 高清晰PDF.pdf";

public static void main(String[] args) {
try {
//文件输入流
File file = new File(filePath);
inputStream = new FileInputStream(file);

//压缩输出路径的流 压缩文件路径+压缩文件名前缀(Linux就该这么学 高清晰PDF)+.zip
outputStream = new FileOutputStream(file.getParent()+"\\"+file.getName().substring(0,file.getName().lastIndexOf("."))+".zip");
zipOutputStream = new ZipOutputStream(outputStream);

//压缩包内文件的名字 Linux就该这么学 高清晰PDF.pdf
zipOutputStream.putNextEntry(new ZipEntry(file.getName()));

//输出文件
byte[] bytes = new byte[1024];
int len = 0;
while ((len = inputStream.read(bytes))!=-1){
zipOutputStream.write(bytes,0,len);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if (zipOutputStream!=null){
zipOutputStream.closeEntry();
zipOutputStream.close();
}
if (outputStream!=null){
outputStream.close();
}
if (inputStream!=null){
inputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

2.单文件解压

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/**
* @author Surpass
* @Package com.hkrt.demo.zip
* @Description: 压缩包解压
* @date 2020/10/16 10:50
*/
public class SingleZipUnpackThe {

private static InputStream inputStream;
private static ZipInputStream bi;
private static OutputStream fileOutputStream;
private static String zipPath = "C:\\Users\\Surpass\\Desktop\\Bypass_1.14.2\\Bypass\\使用须知.zip";

//方法二
public static void main(String[] args) {
try {
//对中文名字进行了处理
ZipFile zipFile = new ZipFile(zipPath, Charset.forName("GBK"));
String zipFileParentPath = zipFile.getName().substring(0,zipFile.getName().lastIndexOf("\\"));
System.out.println(zipFileParentPath);

//获得压缩包内文件
Enumeration<? extends ZipEntry> entries = zipFile.entries();

while (entries.hasMoreElements()) {
ZipEntry zipEntry = entries.nextElement();
//输出文件流 压缩包路径+文件
fileOutputStream = new FileOutputStream(zipFileParentPath+"\\" + zipEntry.getName());
//写文件
byte[] bytes = new byte[1024];
int len = 0;
while ((len = bi.read(bytes))!=-1){
fileOutputStream.write(bytes,0,len);
}
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if (bi!=null){
bi.closeEntry();
bi.close();
}
if (fileOutputStream!=null){
fileOutputStream.close();
}
if (inputStream!=null){
inputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

3.多文件压缩(保留原有结构)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
/**
* @author Surpass
* @Package com.hkrt.demo.zip
* @Description: 多文件根据目录结构压缩
* @date 2020/10/17 10:13
*/
public class MultipleFilesCompression {

private static InputStream inputStream;
private static ZipOutputStream zipOutputStream;
private static OutputStream outputStream;

private static String filePath = "C:\\Users\\Surpass\\Desktop\\Bypass_1.14.25";

public static void main(String[] args) {
try {
//需要压缩的文件夹
File file = new File(filePath);
String dirName = file.getName();
String fileParentPath = file.getParent();

//需要生成的压缩包名称和生成路径
outputStream = new FileOutputStream(fileParentPath+"\\"+dirName+".zip");
zipOutputStream = new ZipOutputStream(outputStream);

//获取目录结构
Map<String,String> map = new HashMap<>();
map = getFile(file, map);

//通过key遍历map
Set<String> keySet = map.keySet();
Iterator<String> iterator = keySet.iterator();
while (iterator.hasNext()){
//key(当是空文件夹的时候key为目录,当文件夹有文件的时候key为文件名)
String fileName = iterator.next();
//value(当是空文件夹的时候value为"",当文件夹有文件的时候value为目录)
String path = map.get(fileName);
if (path.equals("")){
//空文件夹
//这里获取从压缩包开始的路径 \Bypass\Logs>>>>>>2020-09-12.txt \Bypass\Music
String[] basePath = fileName.split(dirName);
String parent = basePath[1];
//压入压缩包流文件的存放路径 \Bypass\Music
zipOutputStream.putNextEntry(new ZipEntry(parent+"/"));
}else {
//正常文件
//文件转输入流
inputStream = new FileInputStream(path+"\\"+fileName);
//这里获取从压缩包开始的路径 \Bypass\Logs>>>>>>2020-09-12.txt \Bypass>>>>>>使用须知.txt
String[] basePath = path.split(dirName);
String parent = basePath[1];
zipOutputStream.putNextEntry(new ZipEntry(parent +"\\"+fileName));
}
//写文件
byte[] bytes = new byte[1024];
int len = 0;
while ((len = inputStream.read(bytes))!=-1){
zipOutputStream.write(bytes,0,len);
}
}
} catch (Exception e) {
e.printStackTrace();
}finally {
//关闭
try {
if (zipOutputStream!=null){
zipOutputStream.closeEntry();
zipOutputStream.close();
}
if (outputStream!=null){
outputStream.close();
}
if (inputStream!=null){
inputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}


/**
* @Description: 使用递归的方式向map中存入目录结构
* @param file, 需要压缩的文件
* map 存放目录结构
* @return java.util.Map<java.lang.String,java.lang.String>
* @throws
* @author Surpass
* @date 2020/10/17 11:26
*/
private static Map<String,String> getFile(File file,Map<String,String> map){
File[] files = file.listFiles();
//如果是空文件夹的时候使用路径作为key
if (files.length==0){
map.put(file.getAbsolutePath(),"");
}
for (File file1 : files) {
if (file1.isDirectory()){
//递归
getFile(file1,map);
}
if (file1.isFile()){
//文件作为key,路径作为value
map.put(file1.getName(),file1.getParent());
}
}
return map;
}
}

4.多文件解压(保留原有结构)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/**
* @author Surpass
* @Package com.hkrt.demo.zip
* @Description: 压缩包解压保持原有的目录
* @date 2020/10/17 11:39
*/
public class MultipleFilesUnpackThe {

private static OutputStream outputStream;
private static InputStream inputStream;
private static ZipInputStream bi;

private static String ZipPath = "C:\\Users\\Surpass\\Desktop\\Bypass.zip";

public static void main(String[] args) {

try {
//对中文名字进行了处理
ZipFile zipFile = new ZipFile(ZipPath, Charset.forName("GBK"));
//压缩包的名字,不包含后缀 .zip
String zipName = zipFile.getName().substring(0, zipFile.getName().indexOf("."));
//压缩包所在的路径
String zipFileParentPath = zipFile.getName().substring(0,zipFile.getName().lastIndexOf("\\"));

Enumeration<? extends ZipEntry> entries = zipFile.entries();

while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
if (entry.isDirectory()) {
//空文件夹,直接创建 压缩包路径+压缩包名字+空文件夹路径
File file = new File(zipFileParentPath+"\\"+zipName+"\\"+entry);
file.mkdirs();
}else {
//获取文件在压缩包内的路径
String entryPath = entry.getName().substring(0,entry.getName().lastIndexOf("\\"));

//为存放的路径创建文件夹
File file = new File(zipFileParentPath+"\\"+zipName+"\\"+entryPath);
if (!file.exists()) {
file.mkdirs();
}
outputStream = new FileOutputStream(zipFileParentPath+"\\"+zipName+"\\"+ entry.getName());
}
//写文件
byte[] bytes = new byte[1024];
int len = 0;
while ((len = bi.read(bytes))!=-1){
outputStream.write(bytes,0,len);
}
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if (bi!=null){
bi.closeEntry();
bi.close();
}
if (inputStream!=null){
inputStream.close();
}
if (outputStream!=null){
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

总结

看网上的例子说有什么jar能简单一下,博主这里没有尝试去看,既然这样写了,也算是一个不错的练习。当然,博主道行较浅,代码不规范是一方面,如果有什么不足之处,还望各位大牛批评指正。