ArchiveUtil.java 1.63 KB
Newer Older
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
package de.hftstuttgart.utils;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.*;
import java.nio.file.Path;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class ArchiveUtil
{
    private static final Logger LOG = LogManager.getLogger(ArchiveUtil.class);

    public static void extractProjectFromZip (InputStream is, Path outDir) throws IOException
    {
        LOG.info(String.format("starting archive extraction to %s", outDir.toAbsolutePath().toString()));
        try (ZipInputStream stream = new ZipInputStream(is)) {

            ZipEntry entry;
            while ((entry = stream.getNextEntry()) != null) {
                File file = outDir.resolve(entry.getName()).toFile();
                LOG.debug(String.format("processing entry %s", file.getAbsolutePath()));

                if (!entry.isDirectory()) {
                    LOG.debug("creating parent folders");
                    file.getParentFile().mkdirs();

                    LOG.debug("creating new file");
                    file.createNewFile();

                    byte[] buffer = new byte[2048];
                    try (FileOutputStream fos = new FileOutputStream(file);
                         BufferedOutputStream bos = new BufferedOutputStream(fos, buffer.length)) {

                        LOG.debug("writing content from zip entry to file");
                        int len;
                        while ((len = stream.read(buffer)) > 0) {
                            bos.write(buffer, 0, len);
                        }
                    }
                }
            }
        }
    }

}