2018년 4월 3일 화요일

[Java] Zip Compress, Decompress Example


1. Zip Compress Example

Download: commons-compress-1.16.1


1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public static void zip(File baseDir, List<File> list, File outFile) throws IOException {
    ZipArchiveOutputStream zos = new ZipArchiveOutputStream(new FileOutputStream(outFile));
    zos.setEncoding(Charset.defaultCharset().name());
    if (list.size() > 0) {
        for (int i = 0; i < list.size(); i++) {
            String entryName = list.get(i).getPath().substring(baseDir.getPath().length()+1);
            zos.putArchiveEntry(new ZipArchiveEntry(entryName));
            FileInputStream fis = new FileInputStream(list.get(i));
            byte[] buf = new byte[8 * 1024];
            int length;        
            while ((length = fis.read(buf, 0, buf.length)) >= 0) {
                zos.write(buf, 0, length);
            }
            fis.close();
            zos.closeArchiveEntry();
        }
    }
    zos.close();
}

static void zipTest() throws IOException {
    Compress cu = new Compress();
    List<File> filelist = new ArrayList<File>();
    filelist.add(new File("c:/temp/a.jar"));
    filelist.add(new File("c:/temp/b/c.jar"));
    File dir = new File("c:/temp");
    File zippedFile = new File ( "c:/temp/test.zip");
    cu.zip(dir, filelist, zippedFile);  
}


Result:




2. Unzip Decompress Example

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public void unzip( File inFile, File destDir)  throws IOException {
    ZipArchiveInputStream zis = new ZipArchiveInputStream(new FileInputStream(inFile), Charset.defaultCharset().name(), false);
    ZipArchiveEntry entry;
    destDir.mkdirs();
    while ( (entry = zis.getNextZipEntry()) != null ){
        String name = entry.getName();
        File target = new File (destDir, name);
        if ( entry.isDirectory() ){
            target.mkdirs();
        } else {
            if( ! target.getParentFile().exists() ) {
                target.getParentFile().mkdirs();
            }
            target.createNewFile();
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(target));
            byte [] buf = new byte[1024 * 8];
            int len = 0;
            while ((len = zis.read(buf)) >= 0 ){
                bos.write(buf, 0, len);
            }
            bos.close();
        }
    }
    zis.close();
}

static void unzipTest() throws IOException {
    Compress cu = new Compress();
    File dir = new File("c:/temp1");
    File zippedFile = new File ( "c:/temp/test.zip");       
    cu.unzip( zippedFile, dir);
}


Result:



3. Unzip Decompress Example using ZipFile

1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipFile;

import javafx.util.Pair;
import net.lingala.zip4j.exception.ZipException;

public class UnzipUtilApache {
    
    public ZipFile zip;
    public List<ZipArchiveEntry> headers;
    public List<Pair<String,Integer>> dirIndex;

    public UnzipUtilApache() {

    }
    
    public UnzipUtilApache(String fileName) throws IOException {
        zip = new ZipFile(fileName);
        initialize();
    }
    
    public UnzipUtilApache(String fileName, String encoding) throws IOException {
        zip = new ZipFile(fileName, encoding);
        initialize();
    }
    
    public void load(String zipFileName) throws IOException {
        zip = new ZipFile(zipFileName);
        initialize();
    }
    
    public void load(String zipFileName, String encoding) throws IOException {
        zip = new ZipFile(zipFileName, encoding);
        initialize();
    }
    
    private void initialize() {
        headers = new ArrayList<>();
        dirIndex = new ArrayList<>();
        Enumeration<ZipArchiveEntry> entries = zip.getEntries();
        while( entries.hasMoreElements() ) {
            ZipArchiveEntry entry = entries.nextElement();
            if( ! entry.isDirectory() ) {
                headers.add(entry);
            }
        }
        SortUtil.sortZipEntry(headers);
        for( ZipArchiveEntry header : headers ) System.out.println(header.getName()); 

        String lastName = "";
        for( int i = 0; i < headers.size(); i++ ) {
            String name = headers.get(i).getName();
            int pos = name.lastIndexOf("/");
            if( pos < 0 ) {
                continue;
            }
            name = name.substring(0,pos);
            if( ! name.equals(lastName) ) {
                lastName = name;
                dirIndex.add(new Pair<>(lastName,i));
            }
        }
        if( dirIndex.size() == 0 ) {
            dirIndex.add( new Pair<>("/",0));
        }        
        for( Pair<String,Integer> dir : dirIndex ) System.out.println(dir.getKey() + ": " + dir.getValue()); 

    }
    
    public int size() {
        return headers.size();
    }
    
    public String getName(int index) {
        return headers.get(index).getName();
    }
    
    public void unzipAllEntry(String targetDir) throws IOException {
        for( ZipArchiveEntry entry : headers ) {
            File file = new File(targetDir, entry.getName() );
            if( ! file.getParentFile().exists() ) {
                file.getParentFile().mkdirs();
            }
            FileUtil.copyStreamToFile(zip.getInputStream(entry), file.getPath());
        }
    }
    
    public byte[] unzipEntry(int index) throws IOException {
        return FileUtil.copyStreamToByteArray(zip.getInputStream(headers.get(index)));
    }
    
    public byte[] unzipEntry(String srcFileName) throws IOException {
        return FileUtil.copyStreamToByteArray(zip.getInputStream(zip.getEntry(srcFileName)));
    }
    
    public void unzipEntry(int index, String fileName) throws IOException {
        FileUtil.copyStreamToFile(zip.getInputStream(headers.get(index)), fileName);
    }
    
    public void unzipEntry(String srcFileName, String fileName) throws IOException {
        FileUtil.copyStreamToFile(zip.getInputStream(zip.getEntry(srcFileName)), fileName);
    }
}


4. Zip Compress Example
1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
public class ZipUtilApache {

    public ZipArchiveOutputStream zip;
    public File baseDirectory;

    public ZipUtilApache(String fileName) throws IOException {
        this(fileName, Charset.defaultCharset().name());
    }
    
    public ZipUtilApache(String fileName, String encoding) throws IOException {
        zip = new ZipArchiveOutputStream(new FileOutputStream(fileName));
        zip.setEncoding(encoding);
    }
    
    public void close() throws IOException {
        zip.close();
    }
    
    public void setBaseDirectory(String baseDirectoryName) {
        baseDirectory = new File(baseDirectoryName); 
    }
    
    public void zipEntry(String fileName, String entryName) throws IOException {
        if( entryName == null ) {
            if( baseDirectory != null ) {
                entryName = fileName.substring(baseDirectory.getPath().length()+1);
            } else {
                return;
            }
        }
        System.out.println(fileName + " -> " + entryName);
        zip.putArchiveEntry(new ZipArchiveEntry(entryName));
        FileInputStream fis = new FileInputStream(fileName);
        byte[] buf = new byte[8 * 1024];
        int length;        
        while ((length = fis.read(buf, 0, buf.length)) >= 0) {
            zip.write(buf, 0, length);
        }
        fis.close();
        zip.closeArchiveEntry();
    }
    
    public void zipEntry(String fileName) throws IOException {
        zipEntry(fileName, null);
    }
}


5. Sort File and Folder Name with Numbers
1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;

import net.lingala.zip4j.model.FileHeader;

public class SortUtil {
    
    public static int compareStringNumber(String s1, String s2) {
        String[] s1Parts = s1.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");
        String[] s2Parts = s2.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");
        int i = 0;
        while(i < s1Parts.length && i < s2Parts.length){
            if(s1Parts[i].compareTo(s2Parts[i]) == 0){ //if parts are the same
                ++i;
            }else{
                try{
                    int intS1 = Integer.parseInt(s1Parts[i]);
                    int intS2 = Integer.parseInt(s2Parts[i]);
                    int diff = intS1 - intS2; 
                    if(diff == 0){
                        ++i;
                    }else{
                        return diff;
                    }
                }catch(Exception ex){
                    return s1.compareTo(s2);
                }
            }
        }
        if(s1.length() < s2.length()){
            return -1;
        }else if(s1.length() > s2.length()){
            return 1;
        }else{
            return 0;
        }
    }  

    public static void sortStringNumber(List<String> strings) {
        Collections.sort(strings, new Comparator<String>() {
            public int compare(String s1, String s2) {
                return compareStringNumber(s1, s2);
            }
        });
    }
    
    public static void sortFiles(List<File> strings) {
        Collections.sort(strings, new Comparator<File>() {
            public int compare(File s1, File s2) {
                return compareStringNumber(s1.getPath(), s2.getPath());
            }
        });
    }
    
    public static void sortZipFileHeader(List<FileHeader> strings) {
        Collections.sort(strings, new Comparator<FileHeader>() {
            public int compare(FileHeader f1, FileHeader f2) {
                return compareStringNumber(f1.getFileName(), f2.getFileName());
            }
        });
    }
    
    public static void sortZipEntry(List<ZipArchiveEntry> strings) {
        Collections.sort(strings, new Comparator<ZipArchiveEntry>() {
            public int compare(ZipArchiveEntry f1, ZipArchiveEntry f2) {
                return compareStringNumber(f1.getName(), f2.getName());
            }
        });
    }

}


댓글 없음:

댓글 쓰기