안드로이드에서 zip, tar.gz 압축 및 압축 해제

13128 단어 안드로이드 진급
프로젝트에 이러한 수요가 있습니다. 내보낼 때 압축 패키지를 내보내야 하고, 가져올 때 압축 패키지를 풀어야 합니다.인터넷에서 적지 않은 코드가 모두 적지 않은 결함을 보았는데, zip이 중국어를 지원하지 않거나, 임의의 디렉터리로 압축하는 것을 지원하지 않아서, 하부를 수정하였다.친측 친개는 쓸 수 있다.jar 패키지 2개, ZipEntry 1개가 필요합니다.jar zip 압축 지원 중국어 하나commons-compress-1.5는 tar와 gz 지원 패키지와 함께 다운로드 주소 압축 jar 패키지 제공
뒤에 tar.gz는 실제적으로 먼저 tar백을 친 후에 gz압축을 하기 때문에 단독 tar백이나 gz압축으로 압축을 풀고 일부 코드를 제거하면 된다
/**
     *   zip             
     * zip  
     */
    private static void compress(File file, com.file.zip.ZipOutputStream out, String basedir)
    {
    /*           */
        if (file.isDirectory())
        {
            compressDirectory(file, out, basedir);
        }
        else
        {
            compressFile(file, out, basedir);
        }
    }

    /**        */
    private static void compressDirectory(File dir, com.file.zip.ZipOutputStream out, String basedir)
    {
        if (!dir.exists()) return;

        File[] files = dir.listFiles();
        for (int i = 0; i < files.length; i++) {
            compress(files[i], out, basedir + dir.getName() + "/");
        }
    }

    /**        */
    private static void compressFile(File file, com.file.zip.ZipOutputStream out, String basedir)
    {
        if (!file.exists()) {
            return;
        }
        try {
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
            com.file.zip.ZipEntry entry = new com.file.zip.ZipEntry(basedir + file.getName());
            out.putNextEntry(entry);
            int count;
            byte data[] = new byte[1024];
            while ((count = bis.read(data)) != -1)
            {
                out.write(data, 0, count);
            }
            bis.close();
        }
        catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void zip(String srcPathName, String zipFileName)
    {
        File file = new File(srcPathName);
        File zipFile = new File(zipFileName);
        if (!file.exists()) throw new RuntimeException(srcPathName + "   !");
        try
        {
            FileOutputStream fileOutputStream = new FileOutputStream(zipFile);
            CheckedOutputStream cos = new CheckedOutputStream(fileOutputStream, new CRC32());
            com.file.zip.ZipOutputStream out = new com.file.zip.ZipOutputStream(cos);
            out.setEncoding(System.getProperty("sun.jnu.encoding"));//         
            String basedir = "";
            compress(file, out, basedir);
            out.close();
        }
        catch (Exception e)
        {
            throw new RuntimeException(e);
        }
    }
/**
     *    zip   
     * @param file     
     * @param dir    *  *
     * @throws IOException
     */
    public static void unzip(File file, String dir) throws IOException {

        //      
        File parent = new File(dir);
        if (!parent.exists()){
            parent.mkdirs();
        }
        ZipFile zipFile = new ZipFile(file, "GBK");//            GBK

        Enumeration entris = zipFile.getEntries();
        ZipEntry zipEntry = null;
        File tmpFile = null;
        BufferedOutputStream bos = null;
        InputStream is = null;
        byte[] buf = new byte[1024];
        int len = 0;
        while (entris.hasMoreElements()) {
            zipEntry = entris.nextElement();

            tmpFile = new File(dir + zipEntry.getName());
            File father = new File(tmpFile.getParent());
            if (!father.exists()){
                father.mkdirs();
            }
            if (zipEntry.isDirectory()) {//       
                if (!tmpFile.exists()) {
                    tmpFile.mkdir();
                }
            } else {
                if (!tmpFile.exists()) {
                    tmpFile.createNewFile();
                }

                is = zipFile.getInputStream(zipEntry);

                bos = new BufferedOutputStream(new FileOutputStream(tmpFile));
                while ((len = is.read(buf)) > 0) {
                    bos.write(buf, 0, len);
                }
                bos.flush();
                bos.close();
            }
        }
/**
     *   tar.gz 
     * @param files      
     * @param destPath     
     */
    public void doTarGZ(File[] files, String destPath)
            throws IOException {
        /*
         *     TarArchiveOutputStream   
         */
        File tarFile = new File(destPath);
        FileOutputStream fos = new FileOutputStream(tarFile);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        TarArchiveOutputStream taos = new TarArchiveOutputStream(bos);
        byte[] buf = new byte[1024];
        for (File child : files) {
            if (child.isFile()) { //   
                FileInputStream fis = new FileInputStream(child);
                BufferedInputStream bis = new BufferedInputStream(fis);
                TarArchiveEntry tae = new TarArchiveEntry(child.getName());
                tae.setSize(child.length());
                taos.putArchiveEntry(tae);
                int len;
                while ((len = bis.read(buf)) > 0) {
                    taos.write(buf, 0, len);
                }
                bis.close();
                taos.flush();
                taos.closeArchiveEntry();
                continue;
            }
        }
        //         
        FileOutputStream gzFile = new FileOutputStream(destPath + ".gz");
        //  gzip     
        GZIPOutputStream gzout = new GZIPOutputStream(gzFile);
        //              
        File file = new File(destPath);
        FileInputStream tarin = new FileInputStream(file);
        int len;
        while ((len = tarin.read(buf)) != -1) {
            gzout.write(buf, 0, len);
        }
        gzout.close();
        gzFile.close();
        tarin.close();
        //  tar   tar.gz
        file.delete();
    }
/**
*tar.gz   
*/
public static void doUnTarGz(File srcfile, String destpath)
            throws IOException {
        byte[] buf = new byte[1024];
        FileInputStream fis = new FileInputStream(srcfile);
        BufferedInputStream bis = new BufferedInputStream(fis);
        GzipCompressorInputStream cis = new GzipCompressorInputStream(bis);
        TarArchiveInputStream tais = new TarArchiveInputStream(cis);
        TarArchiveEntry tae = null;
        int pro = 0;
        while ((tae = tais.getNextTarEntry()) != null) {
            File f = new File(destpath + "/" + tae.getName());
            if (tae.isDirectory()) {
                f.mkdirs();
            } else {
                /*
                 *          
                 */
                File parent = f.getParentFile();
                if (!parent.exists()) {
                    parent.mkdirs();
                }

                FileOutputStream fos = new FileOutputStream(f);
                BufferedOutputStream bos = new BufferedOutputStream(fos);
                int len;
                while ((len = tais.read(buf)) != -1) {
                    bos.write(buf, 0, len);
                }
                bos.flush();
                bos.close();
            }
        }
        tais.close();
    }

좋은 웹페이지 즐겨찾기