JavaSE_IO.ZIP
1.基本原理:
压缩文件的时候每个文件对应一个ZipEntry对象,将文件传入ZipEntry对象中,然后通过putNextEntry方法,将文件写入ZipOutPutStream中,但是如果仅仅这样的话并没有完成压缩文件,ZipEntry并不存储文件内容,所以还需要借助FileInPutStream将文件中的内容读出,然后通过ZipOutPutStram对象中的write方法将文件中的内容输出到ZipOutPutStram中。
2.如何使用Java打压缩包?
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* 将D盘下的Marvel文件夹打压缩包。
*
*/
public class Deam01 {
public static void main(String[] args) {
//1.获取要压缩的文件
File folder = new File("D:\\Marvel");
File[] fileList = folder.listFiles();
//2.创建ZipOutputStream对象,传入生成压缩包的位置
try(ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream
(new FileOutputStream(folder.getName()+File.separator+"out.zip")))) {
//3.遍历要压缩的文件
for (File file : fileList) {
//4.文件传入ZipEntry对象中
ZipEntry entry = new ZipEntry(file.getName());
//5.通过putNextEntry方法写入ZipOutputStream对象中
out.putNextEntry(entry);
//6.创建输入流将文件内容输入到ZipOutputStream对象中
try(BufferedInputStream in = new BufferedInputStream(new FileInputStream(file))){
byte data[] = new byte[8*1024];
int len = -1;
while((len = in.read(data))!=-1) {
out.write(data, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
}
}
//7.关闭zipEntry
out.closeEntry();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
3.如何使用Java解压压缩包?
package com.apesource.deam;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
/**
* 将D盘下的data.zip压缩包解压到D盘根目录下
*
*/
public class Deam03 {
public static void main(String[] args) {
//1.获取压缩包路径。
String zip = "D:\\data.zip";
//2.获取解压到的路径
File folder = new File("D:");
//3.判断该文件夹是否存在(不存在的话创建这个文件夹)
if(!folder.exists()) {
folder.mkdirs();
}
//4.创建ZipInputStream流
try(ZipInputStream in = new ZipInputStream(new BufferedInputStream(new FileInputStream(zip)))){
//5.创建ZipEntry对象
ZipEntry entry = null;
//6.循环获取ZipInputStream中的ZipEntry对象
while((entry = in.getNextEntry())!=null) {
//7.创建解压后的每一个文件。
File file = new File(folder,entry.getName());
//8.创建输出流将压缩包中的内容输入到FileOutputStream对象中
try(BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file))){
int len = -1;
byte data[] = new byte[8*1024];
while((len = in.read(data))!=-1) {
out.write(data, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
4.相关类!
- ZipInputStream类
方法:getNextEntry()获取ZIpInputStream对象中的ZipEntry对象。 - ZipOutputStream类
方法:putNextEntry(entry)将entry对象写入ZipOutputStream对象中。 - ZipEntry类
方法:getName()获取文件名称。