Zip压缩文件
Posted jiminluo
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Zip压缩文件相关的知识,希望对你有一定的参考价值。
package com.gxnu.study.zip;
import java.io.File;
import java.io.FileOutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.junit.Test;
public class ZipEx {
@Test
public void testZip(){
try(
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream("e:/min.zip"));
){
String s1 = "a/b/d/b.ser";
String s2 = "a/b/d/a.xml";
ZipEntry entry = new ZipEntry(s1);
ZipEntry entry2 = new ZipEntry(s2);
zos.putNextEntry(entry);
zos.putNextEntry(entry2);
byte arr[] = Files.readAllBytes(Paths.get("e:","b.ser"));
byte arr1[] = Files.readAllBytes(Paths.get("e:","a.xml"));
zos.write(arr);
zos.write(arr1);
zos.closeEntry();
}catch(Exception e){
e.printStackTrace();
}
}
@Test
public void testMulZip(){
try(
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream("e:/java.zip"));
){
String str = "C:\Users\Jimin\Desktop\three\three";
File file = new File(str);
File[] listFiles = file.listFiles(f->f.isFile());
// Stream.of(listFiles).forEach(System.out::println);
String strRe = ".*(Users\\.*)";//String strRe = ".*(Users/.*)";
Pattern pattern = Pattern.compile(strRe);
int i=0;
String entryName[] = new String[listFiles.length];
for(File temp:listFiles){
String sStr = temp.toString();
// String replace = sStr.replace(‘\‘, ‘/‘);
Matcher matcher = pattern.matcher(sStr);
if(matcher.find()){
String group1 = matcher.group(1);
System.out.println(group1);
entryName[i] = group1;
}
i++;
}
for(i = 0;i<entryName.length;i++){
ZipEntry entry = new ZipEntry(entryName[i]);
zos.putNextEntry(entry);
byte arr[] = Files.readAllBytes(listFiles[i].toPath());
zos.write(arr);
}
zos.closeEntry();
}catch(Exception e){
e.printStackTrace();
}
}
}
以上是关于Zip压缩文件的主要内容,如果未能解决你的问题,请参考以下文章