Java处理压缩文件
一、创建压缩文件
1、创建目录
File zipFile = new File("G:/files/test.zip");
try(ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile)))){
ZipEntry userFolder = new ZipEntry("users/albert/");
out.putNextEntry(userFolder);
out.closeEntry();
}catch(Exception e){
e.printStackTrace();
}
压缩文件结构如下:
└─users
└─albert
2、创建普通文件
File zipFile = new File("G:/files/test.zip");
try(ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile)))){
String introduction = "My name is Albert.";
try(InputStream ins = new ByteArrayInputStream(introduction.getBytes())){
ZipEntry file = new ZipEntry("introduction.txt");
out.putNextEntry(file);
int len = 0;
byte[] buf = new byte[1024];
while ((len = ins.read(buf)) != -1) {
out.write(buf, 0, len);
}
out.closeEntry();
}
}catch(Exception e){
e.printStackTrace();
}
压缩文件结构如下:
introduction.txt
如果要创建指定目录下的文件,只需要指定文件目录即可:
ZipEntry file = new ZipEntry("users/albert/introduction.txt");
压缩文件结构如下:
└─users
└─albert
introduction.txt
二、读取压缩文件
hello.txt
│
└─users
└─albert
introduction.txt
读取如上结构的压缩文件:
File zipFile = new File("G:/files/test.zip");
try(ZipInputStream in = new ZipInputStream(new FileInputStream(zipFile))){
ZipEntry entry = null;
while((entry = in.getNextEntry()) != null){
if(!entry.isDirectory()){
StringBuilder content = new StringBuilder();
ByteArrayOutputStream out = new ByteArrayOutputStream();
int len = 0;
byte[] buf = new byte[1024 * 4];
while ((len = in.read(buf)) != -1) {
out.write(buf, 0, len);
}
byte[] array = out.toByteArray();
content.append(new String(array, 0, array.length, "UTF-8"));
in.closeEntry();
System.out.println(entry.getName() + ": " + content);
}
}
}catch(Exception e){
e.printStackTrace();
}
输出:
hello.txt: Hello World!
users/albert/introduction.txt: My name is Albert.