Java API를 통한 압축 및 zip 압축 형식의 압축 구현
코드 사본은 다음과 같습니다.
패키지 com.hongyuan.test;
import java.io.file;
import java.io.fileInputStream;
import java.io.fileoutputStream;
import java.io.ioexception;
import java.io.inputstream;
import java.io.outputStream;
java.util.enumeration 가져 오기;
java.util.zip.zipentry import;
import java.util.zip.zipfile;
import java.util.zip.zipoutputstream;
공개 클래스 Ziptest {
public static void main (String [] args)은 ioexception {
Unzip ( "bootstrap.zip");
zip ( "bootstrap_01.zip", "bootstrap/css/bootstrap.css", "bootstrap/css/bootstrap.min.css");
}
public static void unzip (String filename)는 ioexception {
// 압축 파일 객체를 가져옵니다
zipfile zf = 새로운 zipfile (filename);
// 파일 항목을 전송합니다
열거 <? Zipentry> items = zf.entries ();
while (items.hasmoreElements ()) {
zipentry item = items.nextElement ();
문자열 filepath = zf.getName (). substring (0,
zf.getName (). lastIndexof ( "."))
+ file.separator + item.getName ();
File Filedir = 새 파일 (Filepath.Substring (0,
filepath.lastindexof ( "/"));
if (! filedir.exists ()) {
filedir.mkdirs ();
}
// 스트림에서 파일을 읽습니다
outputStream out = 새 FileOutputStream (FilePath);
inputStream in = zf.getInputStream (항목);
바이트 [] temp = 새로운 바이트 [1024];
int len = 0;
while ((len = in.read (temp))> 0) {
out.write (Temp, 0, Len);
}
넣다();
out.close ();
}
zf.close ();
}
public static void zip (String filename, string ... files) IoException {
// 압축 파일 출력 스트림을 구성합니다
ZipOutputStream ZOS = New ZipoutPutStream (new FileOutputStream (filename));
for (int i = 0, size = files.length; i <size; i ++) {
// 압축 엔티티를 만듭니다
zipentry entry = new Zipentry (파일 [i] .substring (파일 [i] .lastindexof ( "/")+1));
Zos.putNextEntry (Entry);
// 파일 내용을 압축 스트림으로 출력합니다
inputStream은 = 새 fileInputStream (파일 [i]);
int count = 0;
바이트 [] 버퍼 = 새로운 바이트 [1024];
while (count = is.read (buffer))> = 0) {
Zos.Write (버퍼, 0, count);
}
Zos.flush ();
zos.closeentry ();
is.close ();
}
}
}