티스토리 뷰
import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Enumeration; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; public class ZipUtil { private String zipFileName; private String extractPath; private String osName; private InputStream inputStream; private FileOutputStream outputStream; private File file; private File directories; private static ZipUtil unZip; private ZipUtil( String zipFileName, String extractPath ) { this.zipFileName = zipFileName; this.extractPath = extractPath; this.osName = System.getProperty( "os.name" ); } public static void extractFile( String zipFileName, String extractPath ) { unZip = new ZipUtil( zipFileName, extractPath ); unZip.start(); //start extract. } private void copyStream(InputStream in, OutputStream out) throws Exception { byte buffer[] = new byte[1024]; int len = 0; while ( (len = in.read(buffer) ) != -1) { out.write(buffer, 0, len); } } private String getDirectoryPath(String fullPath) { int pos = fullPath.lastIndexOf('/'); if ( pos == -1 ) { return null; } return fullPath.substring( 0, pos ); } private void start() { try { ZipFile zipFile = new ZipFile(zipFileName); Enumeration en = zipFile.entries(); // nextElement() is called. while (en.hasMoreElements()) { ZipEntry entry = (ZipEntry) en.nextElement(); String entryName = entry.getName(); // check whether file exists. file = new File( extractPath + entryName ); if ( file.exists() ) { //if file exists, skip. continue; } //file extracting. // 1. empty directory if ( entry.isDirectory() || (!osName.equals("unix") && entryName.endsWith("\\")) ) { file.mkdir(); continue; } // 2. regular file, if directory exist first mkdir, and write files. String path = extractPath + getDirectoryPath( entryName ); if ( path != null ) { directories = new File( path ); directories.mkdirs(); } file.createNewFile(); inputStream = zipFile.getInputStream( entry ); outputStream = new FileOutputStream( file ); copyStream( inputStream, outputStream ); inputStream.close(); outputStream.close(); } zipFile.close(); } catch ( Exception e ) { e.printStackTrace(); } finally { if ( inputStream != null ) try { inputStream.close(); } catch ( IOException ioe ) {} if ( outputStream != null ) try { outputStream.close(); } catch ( IOException ioe ) {} } } public static void main(String[] args) { try { ZipUtil.extractFile( "D:/java_document.zip", "D:/" ); } catch ( Exception e ) { e.printStackTrace(); } } }
[출처] http://blog.naver.com/celestialorb
[원본] http://blog.naver.com/celestialorb/40023137374
[작성자] 리바이벌
'Development' 카테고리의 다른 글
[Java] Collections.sort 를 이용한 ArrayList 의 정렬 (0) | 2010.07.02 |
---|---|
[Android] java.lang.IllegalStateException (0) | 2010.07.01 |
[Android] 키패드 보이고 숨기기 (2) | 2010.06.29 |
[Android] View 설명 (0) | 2010.06.29 |
[Android] ListView가 클릭이 안될때... (5) | 2010.06.28 |
최근에 올라온 글
글 보관함
- Total
- Today
- Yesterday