Android

unzip

aucd29 2013. 10. 8. 14:39
// 압축 풀기
Button btnUnzip = (Button) findViewById(R.id.btn_unzip);
btnUnzip.setOnClickListener(new OnClickListener() {

    public void onClick(View v) {
        
        String zipDir = "/sdcard/miniple/";
        String zipFile = "docs.zip";                
        String extractDir = "/sdcard/miniple/extract/docs";

        try {

            File unzipFile = new File(zipDir, zipFile);
            unZip(unzipFile, extractDir);

        } catch (IOException e) {

            // error!!!
            e.printStackTrace();
        }
    }
});

/**
* 압축풀기 메소드
*
* @param unZipFile 압축파일 핸들
* @param extractDir 저장할 경로
* @throws IOException 예외 오류 전달
*/
private void unZip(File unZipFile, String extractDir) throws IOException {
    
    // zip handler
    ZipInputStream in = new ZipInputStream(new FileInputStream(unZipFile));
    ZipEntry ze;

    // create directory
    File dirUnzipFolder = new File(extractDir);
    
    Log.d("miniple", "extract Dir : " + extractDir);

    // checking directory
    if (dirUnzipFolder.exists()) {
        
        Log.d("miniple", "exists");

    } else {
        
        Log.d("miniple", "@@@@ not exists @@@@");
        
        if (!dirUnzipFolder.mkdirs()) {
            throw new IOException("Unable to create folder" + extractDir);
        }
    }
    
    // extract file
    while ((ze = in.getNextEntry()) != null) {

        final String path = extractDir + File.separator + ze.getName();

        //Log.d("miniple", "path : " + path);

        if (ze.getName().indexOf("/") != -1) {
            File parent = new File(path).getParentFile();
            if (!parent.exists()) {
                if (!parent.mkdirs())
                    throw new IOException("Unable to create folder"
                            + parent);
            }
        }

        FileOutputStream out = new FileOutputStream(path);

        byte[] buf = new byte[1024];

        for (int nReadSize = in.read(buf); nReadSize != -1; nReadSize = in.read(buf)) {
            out.write(buf, 0, nReadSize);
        }
        
        out.close();
    }

    in.close();
}