티스토리 뷰

Development

[Java] Zip 압축 풀기

devbible 2010. 6. 30. 09:25


 


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
[작성자] 리바이벌

댓글