Java Basic 클래스를 사용하여 작성된 간단한 지퍼 압축 압축 압축 도구 클래스
코드 사본은 다음과 같습니다.
패키지 sun.net.helper;
java.io.*;
java.util.logging.logger import;
import java.util.zip.*;
공개 수업 ziputil {
개인 최종 정적 로거 로거 = logger.getLogger (ziputil.class.getName ());
개인 정적 최종 int 버퍼 = 1024*10;
/**
* 지정된 디렉토리를 디렉토리와 동일한 이름의 zip 파일로 압축하고 압축 경로를 사용자 정의합니다.
* @param sourceFilePath 대상 파일 경로
* @Param ZipFilePath ZIP 파일 경로를 지정합니다
* @반품
*/
public static boolean zip (String SourceFilePath, String ZipFilePath) {
부울 결과 = 거짓;
파일 소스 = 새 파일 (sourceFilePath);
if (! source.exists ()) {
logger.info (SourceFilePath+"존재하지 않습니다.");
반환 결과;
}
if (! source.isdirectory ()) {
logger.info (sourceFilePath+"는 디렉토리가 아닙니다.");
반환 결과;
}
파일 zipfile = 새 파일 (zipfilepath+"/"+source.getName ()+". Zip");
if (zipfile.exists ()) {
logger.info (zipfile.getName ()+"이미 존재합니다.");
반환 결과;
}또 다른{
if (! zipfile.getParentFile (). Exists ()) {
if (! zipfile.getParentFile (). mkdirs ()) {
logger.info ( "파일을 만들 수 없다"+zipfile.getName ());
반환 결과;
}
}
}
logger.info ( "zip 파일 만들기 ...");
fileoutputStream dest = null;
zipoutputStream out = null;
노력하다 {
dest = new FileOutputStream (ZipFile);
CheckedOutputStream checksum = new CheckedOutputStream (dest, new Adler32 ());
out = new ZipoutputStream (새로운 BufferedOutputStream (Checksum));
out.setMethod (zipoutputStream.deflated);
compress (source, out, source.getName ());
결과 = true;
} catch (filenotfoundException e) {
e.printstacktrace ();
} 마지막으로 {
if (out! = null) {
노력하다 {
out.closeentry ();
} catch (ioexception e) {
e.printstacktrace ();
}
노력하다 {
out.close ();
} catch (ioexception e) {
e.printstacktrace ();
}
}
}
if (결과) {
logger.info ( "완료.");
}또 다른{
logger.info ( "실패");
}
반환 결과;
}
개인 정적 무효 압축 (파일 파일, ZipOutputStream out, String MainFilename) {
if (file.isfile ()) {
fileInputStream fi = null;
bufferedInputStream origin = null;
노력하다 {
fi = 새로운 fileInputStream (파일);
Origin = New BufferedInputStream (fi, buffer);
int index = file.getabsolutepath (). indexof (mainfilename);
String entryname = file.getabsolutepath (). substring (index);
System.out.println (EntryName);
Zipentry Entry = New Zipentry (EntryName);
out.putnextentry (Entry);
바이트 [] data = 새로운 바이트 [버퍼];
int count;
while (count = origin.read (data, 0, buffer))! = -1) {
out.write (data, 0, count);
}
} catch (filenotfoundException e) {
e.printstacktrace ();
} catch (ioexception e) {
e.printstacktrace ();
} 마지막으로 {
if (origin! = null) {
노력하다 {
Origin.Close ();
} catch (ioexception e) {
e.printstacktrace ();
}
}
}
} else if (file.isdirectory ()) {
file [] fs = file.listfiles ();
if (fs! = null && fs.length> 0) {
for (file f : fs) {
압축 (f, out, mainfilename);
}
}
}
}
/**
* 지정된 디렉토리에 zip 파일을 압축하지 않으면이 클래스의 zip 메소드를 사용하여 압축해야합니다.
* @Param ZipFile
* @param destpath
* @반품
*/
공개 정적 부울 unzip (파일 zipfile, string destpath) {
부울 결과 = 거짓;
if (! zipfile.exists ()) {
logger.info (zipfile.getName ()+"존재하지 않는다");
반환 결과;
}
파일 대상 = 새 파일 (destPath);
if (! target.exists ()) {
if (! target.mkdirs ()) {
logger.info ( "파일을 만들 수 없다"+target.getName ());
반환 결과;
}
}
문자열 mainfilename = zipfile.getName (). replace ( ". zip", "");
파일 targetFile = 새 파일 (destPath+"/"+mainFilename);
if (targetfile.exists ()) {
logger.info (targetFile.getName ()+"이미 존재합니다.);
반환 결과;
}
ZipInputStream ZIS = NULL;
logger.info ( "실행 취소 파일 시작 ...");
노력하다 {
fileInputStream fis = 새로운 fileInputStream (ZipFile);
CheckedInputStream checksum = new CheckedInputStream (FIS, New Adler32 ());
ZIS = 새로운 ZipinputStream (새로운 bufferedInputStream (체크섬));
zipentry 항목;
while ((entry = zis.getNextEntry ())! = null) {
int count;
바이트 데이터 [] = 새로운 바이트 [버퍼];
문자열 entryName = entry.getName ();
int index = EntryName.IndExOf (mainFilename);
string newEntryName = destPath+"/"+EntryName.SubString (index);
System.out.println (NewentryName);
file temp = 새 파일 (newentryName) .getParentFile ();
if (! temp.exists ()) {
if (! temp.mkdirs ()) {
새로운 runtimeexception을 던지십시오 ( "파일 만들기" +temp.getName () +"fail");
}
}
fileoutputStream fos = new FileOutputStream (newEntryName);
BufferedOutputStream dest = new BufferedOutputStream (FOS, 버퍼);
while ((count = zis.read (data, 0, buffer))! = -1) {
dest.write (data, 0, count);
}
dest.flush ();
dest.close ();
}
결과 = true;
} catch (filenotfoundException e) {
e.printstacktrace ();
} catch (ioexception e) {
e.printstacktrace ();
} 마지막으로 {
if (zis! = null) {
노력하다 {
zis.close ();
} catch (ioexception e) {
e.printstacktrace ();
}
}
}
if (결과) {
logger.info ( "완료.");
}또 다른{
logger.info ( "실패");
}
반환 결과;
}
public static void main (String [] args)은 ioexception {
//ziputil.zip("d:/apache-tomcat-7.0.30 ","d :/temp ");
file zipfile = 새 파일 ( "d : /temp/apache-tomcat-7.0.zip");
ziputil.unzip (zipfile, "d :/temp");
}
}
다른 압축 및 감압 예제, 두 도구를 참조하십시오.
코드 사본은 다음과 같습니다.
패키지 com.lanp;
import java.io.file;
import java.io.fileInputStream;
import java.io.fileoutputStream;
import java.io.ioexception;
java.util.zip.zipentry import;
java.util.zip.zipexception import;
import java.util.zip.zipfile;
import java.util.zip.zipinputstream;
/**
* 지정된 디렉토리로 압축 된 파일을 압축 해제
*/
공개 최종 클래스 ziptofile {
/**
* 캐시 크기는 기본값이 20480입니다
*/
개인 최종 정적 int file_buffer_size = 20480;
private ziptofile () {
}
/**
* 지정된 디렉토리의 zip 압축 파일을 지정된 디렉토리로 압축 해제합니다.
* @param zipfilepathzip 압축 파일 경로
* @param zipfilenamezip 압축 파일 이름
* @param targetFileDirzip 압축 된 파일을 추출합니다
* @return 플래그 부울 반환 값
*/
public static boolean unzip (String ZipFilePath, String ZipFilename, String TargetFiledir) {
부울 플래그 = 거짓;
// 1. 1. 압축 파일이 존재하고 내부의 내용이 비어 있는지 결정합니다.
파일 = null; // 압축 파일 (경로 포함)
zipfile zipfile = null;
file = 새 파일 (ZipFilePath + "/" + ZipFilename);
System.out.println ( ">>>>>>> 파일 [" + zipfilepath + "/" + zipfilename + "]를 [" + targetFileDir + "] directory <<<<<<<")에 압축 해제합니다.
if (false == file.exists ()) {
System.out.println ( ">>>>>>> 압축 파일 [" + zipfilepath + "/" + zipfilename + "] 존재하지 않습니다 <<<<<<<");
거짓을 반환합니다.
} else if (0 == file.length ()) {
System.out.println ( ">>>>>> 압축 파일 [" + ZipFilePath + "/" + ZipFilename + "] 크기는 0이고 감압이 필요하지 않습니다 <<<<<");
거짓을 반환합니다.
} 또 다른 {
// 2. 시작 시작 zip 압축 파일
바이트 [] buf = 새로운 바이트 [file_buffer_size];
int readsize = -1;
ZipInputStream ZIS = NULL;
fileoutputStream fos = null;
노력하다 {
// ZIP 파일인지 확인하십시오
zipfile = 새로운 zipfile (파일);
zipfile.close ();
// 대상 디렉토리가 존재하지 않는지 결정하십시오
file newdir = 새 파일 (TargetFileDir);
if (false == newdir.exists ()) {
newdir.mkdirs ();
newdir = null;
}
zis = new ZipinputStream (new FileInputStream (file));
zipentry zipentry = zis.getNextEntry ();
// 압축 패키지에서 파일 처리를 시작합니다
while (null! = zipentry) {
String ZipentRyName = zipentry.getName (). replace ( '//', '/');
// Zipentry가 디렉토리인지 판단하십시오
if (zipentry.isdirectory ()) {
int indexnumber = zipentryname.lastIndexof ( '/');
file entrydirs = 새 파일 (TargetFiledir + "/" + ZipentRyName.SubString (0, indexNumber));
EntryDirs.mkdirs ();
EntryDirs = null;
} 또 다른 {
노력하다 {
FOS = 새 FILEOUTPUTSTREAM (TargetFileDir + "/" + ZipentRyName);
while ((readsize = zis.read (buf, 0, file_buffer_size)! = -1) {
fos.write (buf, 0, readsize);
}
} catch (예외 e) {
e.printstacktrace ();
새로운 runtimeexception 던지기 (e.getCause ());
} 마지막으로 {
노력하다 {
if (null! = fos) {
fos.close ();
}
} catch (ioexception e) {
e.printstacktrace ();
새로운 runtimeexception 던지기 (e.getCause ());
}
}
}
zipentry = zis.getNextEntry ();
}
flag = true;
} catch (ZipException e) {
e.printstacktrace ();
새로운 runtimeexception 던지기 (e.getCause ());
} catch (ioexception e) {
e.printstacktrace ();
새로운 runtimeexception 던지기 (e.getCause ());
} 마지막으로 {
노력하다 {
if (null! = zis) {
zis.close ();
}
if (null! = fos) {
fos.close ();
}
} catch (ioexception e) {
e.printstacktrace ();
새로운 runtimeexception 던지기 (e.getCause ());
}
}
}
리턴 플래그;
}
/**
* 테스트를위한 주요 방법
*/
public static void main (String [] args) {
문자열 ZipFilePath = "C : // home";
문자열 zipfilename = "lp20120301.zip";
문자열 targetFiledir = "C : // home // lp20120301";
부울 플래그 = ziptofile.unzip (zipfilepath, zipfilename, targetfiledir);
if (플래그) {
System.out.println ( ">>>>>>> 성공적으로 <<<<<<<";
} 또 다른 {
System.out.println ( ">>>>>>> 감압 실패 <<<<<<");
}
}
}