괴도군의 블로그

[JAVA] Zip code 압축코드 풀소스입니다. 자바로 압축하기 본문

#프로그래밍/JAVA

[JAVA] Zip code 압축코드 풀소스입니다. 자바로 압축하기

괴도군 2017. 7. 21. 17:05
반응형

안녕하세요. 괴도입니다.

인터넷상에 떠도는 압축소스가 전부다 마음에 들지않네요..

폴더구조까지 통채로 압축하는 코드 올립니다.

압축을 풀때도 폴더구조로 풀게됩니다.

ZIP_FROM_PATH가 중간에 있는데, 압축대상경로입니다.

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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
/**
     * 디렉토리 및 파일을 압축한다.
     * @param path 압축할 디렉토리 및 파일
     * @param toPath 압축파일을 생성할 경로
     * @param fileName 압축파일의 이름
     */
    public static void createZipFile(String path, String toPath, String fileName) {
 
        File dir = new File(path);
        String[] list = dir.list();
        String _path;
 
        if (!dir.canRead() || !dir.canWrite())
            return;
 
        int len = list.length;
 
        if (path.charAt(path.length() - 1!= '/')
            _path = path + "/";
        else
            _path = path;
 
        try {
            ZipOutputStream zip_out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(toPath+"/"+fileName), 2048));
 
            for (int i = 0; i < len; i++)
                zip_folder("",new File(_path + list[i]), zip_out);
 
            zip_out.close();
 
        } catch (FileNotFoundException e) {
            Log.e("File not found", e.getMessage());
 
        } catch (IOException e) {
            Log.e("IOException", e.getMessage());
        } finally {
 
 
        }
    }
 
    /**
     * ZipOutputStream를 넘겨 받아서 하나의 압축파일로 만든다.
     * @param parent 상위폴더명
     * @param file 압축할 파일
     * @param zout 압축전체스트림
     * @throws IOException
     */
    private static void zip_folder(String parent, File file, ZipOutputStream zout) throws IOException {
        byte[] data = new byte[2048];
        int read;
 
        if (file.isFile()) {
            ZipEntry entry = new ZipEntry(parent + file.getName());
            zout.putNextEntry(entry);
            BufferedInputStream instream = new BufferedInputStream(new FileInputStream(file));
 
            while ((read = instream.read(data, 02048)) != -1)
                zout.write(data, 0, read);
 
            zout.flush();
            zout.closeEntry();
            instream.close();
 
        } else if (file.isDirectory()) {
            String parentString = file.getPath().replace(ZIP_FROM_PATH,"");
            parentString = parentString.substring(0,parentString.length() - file.getName().length());
            ZipEntry entry = new ZipEntry(parentString+file.getName()+"/");
            zout.putNextEntry(entry);
 
            String[] list = file.list();
            if (list != null) {
                int len = list.length;
                for (int i = 0; i < len; i++) {
                    zip_folder(entry.getName(),new File(file.getPath() + "/" + list[i]), zout);
                }
            }
        }
    }
 
    /**
     * 압축을 해제 한다
     *
     * @param zip_file
     * @param directory
     */
    public static boolean extractZipFiles(String zip_file, String directory) {
        boolean result = false;
 
        byte[] data = new byte[2048];
        ZipEntry entry = null;
        ZipInputStream zipstream = null;
        FileOutputStream out = null;
 
        if (!(directory.charAt(directory.length() - 1== '/'))
            directory += "/";
 
        File destDir = new File(directory);
        boolean isDirExists = destDir.exists();
        boolean isDirMake = destDir.mkdirs();
 
        try {
            zipstream = new ZipInputStream(new FileInputStream(zip_file));
 
            while ((entry = zipstream.getNextEntry()) != null) {
 
                int read = 0;
                File entryFile;
 
                //디렉토리의 경우 폴더를 생성한다.
                if (entry.isDirectory()) {
                    File folder = new File(directory+entry.getName());
                    if(!folder.exists()){
                        folder.mkdirs();
                    }
                    continue;
                }else {
                    entryFile = new File(directory + entry.getName());
                }
 
                if (!entryFile.exists()) {
                    boolean isFileMake = entryFile.createNewFile();
                }
 
                out = new FileOutputStream(entryFile);
                while ((read = zipstream.read(data, 02048)) != -1)
                    out.write(data, 0, read);
 
                zipstream.closeEntry();
 
            }
 
            result = true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            result = false;
        } catch (IOException e) {
            e.printStackTrace();
            result = false;
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
 
            if (zipstream != null) {
                try {
                    zipstream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
 
        return result;
    }
cs


반응형
Comments