Java解压缩档案文件

时间:2018-11-21 03:14:12

标签: java gzip java-io compression ziparchive

我写了下面的程序来提取存档文件。尽管它可以按要求工作,但我想就提高其性能和降低代码复杂性的可能方法,或者是否可以以一种更简单的方式获得结果的方法,向您提出建议。

此外,在commonExtracter方法中,不是间歇性地创建目录,而是可以利用临时文件夹来完成相同的工作?最后一步应该类似于创建目录并将解压缩的temp文件夹放在其中。

public class ExtractAllArchives {

    public static void main(String[] args) {
        File archiveFileLocation = new File("C:\\ZIP\\Sample.tar.gz");
//      File archiveFileLocation = new File("C:\\ZIP\\Root.zip");
        File destination = null;

        try {
            destination = new File(archiveFileLocation.getParent() + File.separator
                    + FilenameUtils.getBaseName(archiveFileLocation.getName()));
            if (destination.exists()) {
                FileUtils.deleteDirectory(destination);
            }
            destination.mkdir();
        } catch (IOException e) {
            e.printStackTrace();
        }

        String fileExtn = FilenameUtils.getExtension(archiveFileLocation.getAbsolutePath());
        String outputFolder = destination.getAbsolutePath();
        switch (fileExtn) {
        case "gz":
            try (TarArchiveInputStream ais = new TarArchiveInputStream(
                    new GzipCompressorInputStream(new BufferedInputStream(new FileInputStream(archiveFileLocation))))) {
                commonExtracter(ArchiveStreamFactory.TAR, ais, outputFolder);
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            break;
        case "zip":
            try (ArchiveInputStream ais = new ArchiveStreamFactory().createArchiveInputStream(ArchiveStreamFactory.ZIP,
                    new FileInputStream(archiveFileLocation))) {
                commonExtracter(ArchiveStreamFactory.ZIP, ais, outputFolder);
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            break;
        default:
            System.out.println("No archive extractor found");
        }
        System.out.println("File extraction completed");
    }

    private static void commonExtracter(String archiveName, ArchiveInputStream ais, String outputFolder) {
        ArchiveEntry entry = null;
        try {
            while ((entry = ais.getNextEntry()) != null) {
                String filePath = outputFolder + File.separator + entry.getName();
                Path fileLoc = Paths.get(filePath);
                if (entry.isDirectory()) {
                    new File(filePath).mkdirs();
                } else {
                    try (OutputStream bos = Files.newOutputStream(fileLoc)) {
                        IOUtils.copy(ais, bos);
                    } catch (Exception e) {
                        System.out.println("Failed to create the output file");
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

Any help on this topic is much appreciated.

Thank you.

0 个答案:

没有答案