본문 바로가기
코드

unzip

by umaking 2010. 8. 3.
 
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public boolean unzip(String sourceFile, String targetPath) {
  boolean flag = false;
  ZipFile zip = null;
  InputStream is = null;
  FileOutputStream fo = null;
  File f = null;
  zipList = new ArrayList<String>();
  try {
		zip = new ZipFile(new File(sourceFile));
		Enumeration<? extends ZipEntry> e = zip.entries();
		while(e.hasMoreElements()) {
			 flag = false;
			 ZipEntry entry = (ZipEntry)e.nextElement();
			 String path = targetPath + "/" + entry.getName();
			 zipList.add(entry.getName() + " (" + entry.getSize() + "bytes)");
			 System.out.println(entry.getName() + " " + entry.getSize());

			 if(entry.isDirectory()) {
				  f = new File(path);
				  f.mkdirs();
				  flag = true;
			 }else {
				  int pos = path.lastIndexOf("/");
				  if(pos != -1) {
						is = zip.getInputStream(entry);
						f = new File(path.substring(0, pos));
						f.mkdirs();
						f = new File(path);
						byte[] data = new byte[maxBuffSize];
						int len = 0;
						fo = new FileOutputStream(f);
						while((len = is.read(data)) != -1) {
							 fo.write(data, 0, len);
						}
						fo.close();
						is.close();
						flag = true;
				  }
			 }
		}
		zip.close();
  }catch (Exception e) {
		e.printStackTrace();
  }finally {
		if(fo != null) try { fo.close(); } catch (Exception e) { }
		if(is != null) try { is.close(); } catch (Exception e) { }
		if(zip != null) try { zip.close(); } catch (Exception e) { }
  }
  return flag;
}

public StringBuffer getEntry(String sourceFile, String entryStr) {
  StringBuffer sb = new StringBuffer();
  ZipFile zip = null;
  InputStream is = null;
  try {
		zip = new ZipFile(new File(sourceFile));
		ZipEntry entry = zip.getEntry(entryStr);
		is = zip.getInputStream(entry);
		int len;
		byte[] data = new byte[0xff];
		while((len = is.read(data)) != -1) {
			 sb.append(new String(data));
		}
		is.close();
		zip.close();
  }catch (Exception e) {
		e.printStackTrace();
  }finally {
		if(is != null) try { is.close(); } catch (Exception e) { }
		if(zip != null) try { zip.close(); } catch (Exception e) { }
  }
  return sb;
}

'코드' 카테고리의 다른 글

WebDAV (FireMonkey)  (0) 2014.06.27
Cam  (0) 2010.08.10
FindWindow  (0) 2010.07.13
SQLPLUS에서 SQL DDL Export  (0) 2009.11.11
GNUstep Make파일을 만들다.  (0) 2009.10.22