자바 압축 풀기

17754 단어
압축 풀기
도구 종류:
package com.mazaiting;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GzipUtil {
    /**utf-8  */
    public static final String GZIP_ENCODE_UTF_8 = "UTF-8";
    /**iso-8859-1  */
    public static final String GZIP_ENCODE_ISO_8859_1 = "ISO-8859-1";
    
    
    /**
     * "utf-8"    
     * @param string        
     * @return     
     */
    public static byte[] compress(String string) {
        return compress(string, GZIP_ENCODE_UTF_8);
    }

    /**
     *       
     * @param string        
     * @param encoding   
     * @return     
     */
    public static byte[] compress(String string, String encoding) {
        //       
        if (null == string || string.length() == 0) {
            return null;
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        GZIPOutputStream gzipOutputStream;
        try {
            gzipOutputStream = new GZIPOutputStream(baos);
            gzipOutputStream.write(string.getBytes(encoding));
            gzipOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return baos.toByteArray();
    }

    /**
     *        
     * @param bytes         
     * @return     
     */
    public static byte[] uncompress(byte[] bytes) {
        if (null == bytes || bytes.length == 0) {
            return null;
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
        GZIPInputStream unGzip;
        try {
            unGzip = new GZIPInputStream(bais);
            byte[] buffer = new byte[256];
            int n;
            while ((n = unGzip.read(buffer)) >= 0) {
                baos.write(buffer, 0, n);               
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return baos.toByteArray();
    }

    /**
     * "utf-8"    
     * @param bytes         
     * @return     
     */
    public static String uncompressToString(byte[] bytes) {
        return uncompressToString(bytes, GZIP_ENCODE_UTF_8);
    }

    /**
     *       
     * @param string        
     * @param encoding   
     * @return     
     */
    public static String uncompressToString(byte[] bytes, String encoding) {
        if (null == bytes || bytes.length == 0) {
            return null;
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
        GZIPInputStream unGzip;
        try {
            unGzip = new GZIPInputStream(bais);
            byte[] buffer = new byte[256];
            int n;
            while ((n = unGzip.read(buffer)) >= 0) {
                baos.write(buffer, 0, n);               
            }
            return baos.toString(encoding);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}


구체 적 인 사용:
package com.mazaiting;

public class Test {
    public static void main(String[] args) {
        String string = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
        System.out.println("     : " + string.length());
        System.out.println("   : " + GzipUtil.compress(string).length);
        System.out.println("   : " + GzipUtil.uncompress(GzipUtil.compress(string)).length);
        System.out.println("        : " + GzipUtil.uncompressToString(GzipUtil.compress(string)).length());
    }
}


2. Zip 압축 풀기
글 에 필요 한 도구 클래스 자바 파일 옮 겨 다 니 기
  • 도구 류
  •  
    /**
     * Zip       
     * @author mazaiting
     */
    public class ZipUtil {
        /**    --1M*/
        private static final int BUFF_SIZE = 1024 * 1024;
        
        /**
         *       (   )
         * @param resFileList       ( )  
         * @param zipFile        
         * @throws IOException           
         */
        public static void zipFiles(Collection resFileList, File zipFile) throws IOException {
            ZipOutputStream zipOut = new ZipOutputStream(
                    new BufferedOutputStream(new FileOutputStream(zipFile), BUFF_SIZE));
            for (File resFile : resFileList) {
                zipFile(resFile, zipOut, "");
            }
            zipOut.close();
        }
        
        /**
         *       (   )
         * @param resFileList       ( )  
         * @param zipFile        
         * @param comment        
         * @throws IOException            
         */ 
        public static void zipFiles(Collection resFileList, File zipFile, String comment) throws IOException {
            ZipOutputStream zipOut = new ZipOutputStream(
                    new BufferedOutputStream(new FileOutputStream(zipFile), BUFF_SIZE));
            for (File resFile : resFileList) {
                zipFile(resFile, zipOut, "");
            }
            zipOut.setComment(comment);
            zipOut.close();
        }
        
        /**
         *        
         * @param zipFile     
         * @param folderPath         
         * @throws IOException 
         * @throws ZipException 
         */
        public static void upZipFile(File zipFile, String folderPath) throws ZipException, IOException {
            //           
            File desDir = new File(folderPath);
            //         ,        
            if (!desDir.exists()) {
                desDir.mkdirs();
            }
            //         
            ZipFile zFile = new ZipFile(zipFile);
            //     
            for (Enumeration> entries = zFile.entries(); entries.hasMoreElements(); ){
                ZipEntry entry = (ZipEntry) entries.nextElement();
                InputStream in = zFile.getInputStream(entry);
                String str = folderPath + File.separator + entry.getName();
                str = new String(str.getBytes("8859_1"), "GB2312");
                File desFile = new File(str);
                //         
                if (!desFile.exists()) {
                    File fileParentDir = desFile.getParentFile();
                    //           
                    if (!fileParentDir.exists()) {
                        fileParentDir.mkdirs();
                    }
                    //      
                    desFile.createNewFile();
                }
                OutputStream out = new FileOutputStream(desFile);
                byte[] buffer = new byte[BUFF_SIZE];
                int realLength;
                while ((realLength = in.read(buffer)) >0) {
                    out.write(buffer, 0, realLength);
                }
                in.close();
                out.close();
            }
            
        }
        
        /**
         *               
         * @param zipFile     
         * @param folderPath      
         * @param nameContains         
         * @throws ZipException          
         * @throws IOException IO     
         */
        public static ArrayList upZipSelectedFile(File zipFile, String folderPath,
                String nameContains) throws ZipException, IOException {
            ArrayList fileList = new ArrayList();
     
            File desDir = new File(folderPath);
            if (!desDir.exists()) {
                desDir.mkdir();
            }
     
            ZipFile zf = new ZipFile(zipFile);
            for (Enumeration> entries = zf.entries(); entries.hasMoreElements();) {
                ZipEntry entry = ((ZipEntry)entries.nextElement());
                if (entry.getName().contains(nameContains)) {
                    InputStream in = zf.getInputStream(entry);
                    String str = folderPath + File.separator + entry.getName();
                    str = new String(str.getBytes("8859_1"), "GB2312");
                    // str.getBytes("GB2312"),"8859_1"   
                    // str.getBytes("8859_1"),"GB2312"   
                    File desFile = new File(str);
                    if (!desFile.exists()) {
                        File fileParentDir = desFile.getParentFile();
                        if (!fileParentDir.exists()) {
                            fileParentDir.mkdirs();
                        }
                        desFile.createNewFile();
                    }
                    OutputStream out = new FileOutputStream(desFile);
                    byte buffer[] = new byte[BUFF_SIZE];
                    int realLength;
                    while ((realLength = in.read(buffer)) > 0) {
                        out.write(buffer, 0, realLength);
                    }
                    in.close();
                    out.close();
                    fileList.add(desFile);
                }
            }
            return fileList;
        }
        
    
        /**
         *     
         * @param resFile        ( )
         * @param zipOut        
         * @param rootPath        
         * @throws IOException 
         */
        private static void zipFile(File resFile, ZipOutputStream zipOut, String rootPath) throws IOException {
            //             0,   0 string "/",   0  ""
            String string = rootPath.trim().length() == 0 ? "" : File.separator;
            //          
            rootPath = rootPath + string + resFile.getName();
            //     
            rootPath = new String(rootPath.getBytes("8859_1"), "GB2312");
            //           
            if (resFile.isDirectory()) {
                //             
                File[] listFiles = resFile.listFiles();
                for (File file : listFiles) {
                    zipFile(file, zipOut, rootPath);
                }
            } else {
                byte[] buffer = new byte[BUFF_SIZE];
                BufferedInputStream in = new BufferedInputStream(
                        new FileInputStream(resFile), BUFF_SIZE);
                zipOut.putNextEntry(new ZipEntry(rootPath));
                int realLength;
                while ((realLength = in.read(buffer)) != -1) {
                    zipOut.write(buffer, 0, realLength);                
                }
                in.close();
                zipOut.flush();
                zipOut.closeEntry();
            }
        }
        
        /**
         *            
         * @param zipFile     
         * @return          
         * @throws IOException 
         * @throws ZipException 
         */
        public static ArrayList getEntriesNames(File zipFile) throws ZipException, IOException {
            ArrayList entryNames = new ArrayList<>();
            Enumeration> entries = getEntriesEnumeration(zipFile);
            while (entries.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) entries.nextElement();
                entryNames.add(new String(
                        getEntryName(entry).getBytes("GB2312"), "8859_1"));
            }
            return entryNames;
        }
    
        /**
         *            
         * @param entry       
         * @return          
         * @throws UnsupportedEncodingException 
         */
        private static String getEntryName(ZipEntry entry) throws UnsupportedEncodingException {
            return new String(entry.getName().getBytes("GB2312"), "8859_1");
        }
    
        /**
         *            
         * @param entry       
         * @return          
         * @throws UnsupportedEncodingException 
         */
        public static String getEntryComment(ZipEntry entry) throws UnsupportedEncodingException {
            return new String(entry.getComment().getBytes("GB2312"), "8859_1");
        }
        
        /**
         *                    
         * @param zipFile     
         * @return           
         * @throws IOException 
         * @throws ZipException 
         */
        private static Enumeration> getEntriesEnumeration(File zipFile) throws ZipException, IOException {
            ZipFile zf = new ZipFile(zipFile);
            return zf.entries();
        }   
    }
    
    
  • 사용
  • public class Test {
        public static void main(String[] args) throws IOException {
            ArrayList listFiles = DirTraversal.listFiles("E:\\web");
            for (File file : listFiles) {
                System.out.println(file.getAbsolutePath());
            }
            
    
            File zipFile = new File("E:\\web\\file.zip");
            ZipUtil.zipFiles(listFiles, zipFile);
            
    //      File zipFile = new File("E:\\web\\file.zip");
    //      ZipUtil.zipFiles(listFiles, zipFile, "Hello");
            
    //      File zipFile = new File("E:\\web\\file.zip");
    //      ZipUtil.upZipFile(zipFile, "E:\\web");
            
        }
    }
    

    3. 아파 치 커 먼 스 압축 풀기
    AR, cpio, Unix dump, tar, zip, gzip, XZ, Pack 200, bzip 2, 7z, arj, lzma, snappy, DEFLATE, lz4, Brotli and Z files 형식 을 지원 합 니 다.
    
    /**
     * BZip2      
     * @author mazaiting
     */
    public class BZip2Util {
        /**    */
        public static final int BUFFER = 1024;
        /**   */
        public static final String EXT = ".bz2";
        
        /**
         *     
         * @param data     
         * @return
         * @throws IOException 
         */
        public static byte[] compress(byte[] data) throws IOException {
            ByteArrayInputStream bais = new ByteArrayInputStream(data);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            //   
            compress(bais, baos);
            
            byte[] output = baos.toByteArray();
            
            //         
            baos.flush();
            //    
            baos.close();
            bais.close();
            
            return output;      
        }
        
        /**
         *     
         * @param file   
         * @param delete        
         * @throws IOException 
         */
        public static void compress(File file, boolean delete) throws IOException {
            FileInputStream fis = new FileInputStream(file);
            FileOutputStream fos = new FileOutputStream(file.getPath() + EXT);
            
            compress(fis, fos);
            
            fos.flush();
            
            fos.close();
            fis.close();
            
            if (delete) {
                file.delete();
            }
        }
    
        /**
         *     
         * @param is     
         * @param os    
         * @throws IOException 
         */
        private static void compress(InputStream is, OutputStream os) throws IOException {
            BZip2CompressorOutputStream bcos = new BZip2CompressorOutputStream(os);
            
            int count;
            byte data[] = new byte[BUFFER];
            
            while((count = is.read(data, 0, BUFFER)) != -1){
                bcos.write(data, 0, count);
            }
            
            bcos.finish();
            
            bcos.flush();
            bcos.close();       
        }
        
        /**
         *     
         * @param path     
         * @param delete        
         * @throws IOException 
         */
        public static void compress(String path, boolean delete) throws IOException{
            File file = new File(path);
            compress(file, delete);
        }
        
        /**
         *      
         * @param data   
         * @return 
         * @throws IOException 
         */
        public static byte[] deCompress(byte[] data) throws IOException{
            ByteArrayInputStream bais = new ByteArrayInputStream(data);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            
            //    
            deCompress(bais, baos);
            
            data = baos.toByteArray();
            
            baos.flush();
            baos.close();
            bais.close();
            
            return data;
        }
    
        /**
         *      
         * @param file   
         * @param delete        
         * @throws IOException 
         */
        public static void deCompress(File file, boolean delete) throws IOException{
            FileInputStream fis = new FileInputStream(file);
            FileOutputStream fos = new FileOutputStream(file.getPath().replace(EXT, ""));
            
            deCompress(fis, fos);
            
            fos.flush();
            fos.close();
            fis.close();
            
            if (delete) {
                file.delete();
            }
        }
        
        /**
         *    
         * @param is    
         * @param os    
         * @throws IOException 
         */
        private static void deCompress(InputStream is, OutputStream os) throws IOException {
            BZip2CompressorInputStream bcis = new BZip2CompressorInputStream(is);
            
            int count;
            byte data[] = new byte[BUFFER];
            
            while((count = bcis.read(data, 0, BUFFER)) != -1){
                os.write(data, 0, count);
            }
            
            bcis.close();
        }
        
        /**
         *      
         * @param path     
         * @param delete        
         * @throws IOException 
         */
        public static void deCompress(String path, boolean delete) throws IOException{
            File file = new File(path);
            deCompress(file, delete);
        }
            
    }   
    

    위 는 BZip 2 압축 코드 입 니 다. 다른 형식의 압축 을 풀 려 면 코드 에 있 는 BZip2Compressor InputStream 과 BZip2Compressor OutputStream 을 대응 하 는 교체 하면 됩 니 다.
  • . ar 대응 ArArchive InputStream 과 ArArchive OutputStream
  • . cpio 는 CpioArchive InputStream 과 CpioArchive OutputStream
  • 에 대응 합 니 다.
  • . dump 대응 DumpArchive InputStream
  • . tar 대응 TarArchive InputStream 과 TarArchive OutputStream
  • . zip 대응 ZipArchive InputStream 과 ZipArchive OutputStream
  • . gzip 대응 GzipCompressor InputStream 과 GzipCompressor OutputStream
  • . xz 대응 XZCompressor InputStream 과 XZCompressor OutputStream
  • . pack 200 대응 Pack 200 Compressor InputStream 과 Pack 200 Compressor OutputStream
  • . bzip 2 대응 BZip2Compressor InputStream 과 BZip2Compressor OutputStream
  • . 7z 대응 SevenzFile 과 SevenzOutput File
  • . arj 대응 ArjArchive InputStream
  • . lzma 는 LZMA Compressor InputStream 과 LZMA Compressor OutputStream
  • 에 대응 합 니 다.
  • . snappy 대응 SnappyCompressor InputStream 과 SnappyCompressor OutputStream
  • . deflate 는 Deflate Compressor InputStream 과 Deflate Compressor OutputStream
  • 에 대응 합 니 다.
  • . lz4 대응 BlockLZ4Compressor InputStream 과 BlockLZ4Compressor OutputStream
  • . brotli 대응 BrotliCompressor InputStream
  • . z 대응 ZCompressorInputStream
  • 좋은 웹페이지 즐겨찾기