1. 程式人生 > >Zip壓縮文件

Zip壓縮文件

n) class user repl pack cep zip壓縮 leo str

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壓縮文件