Как распаковать BZIP (не BZIP2) с помощью Apache Commons - PullRequest
0 голосов
/ 04 июня 2019

Я работал над задачей распаковки из различных типов файлов, таких как "zip, tar, tbz, tgz" . Я могу сделать для всех, кроме ТБЗ, потому что Apache Common Compress Библиотека предоставляет компрессоры BZIP2. Но мне нужно распаковать старый BZIP, а не BZIP2. Есть ли способ сделать это Java. Я добавил код, который я до сих пор делал для извлечения различных архивов tar-файлов с использованием библиотеки Apache Commons ниже.

public List<ArchiveFile> processTarFiles(String compressedFilePath, String fileType) throws IOException {
    List<ArchiveFile> extractedFileList = null;
    TarArchiveInputStream is = null;
    FileOutputStream fos = null;
    BufferedOutputStream dest = null;
    try {
        if(fileType.equalsIgnoreCase("tar"))
        {
            is = new TarArchiveInputStream(new FileInputStream(new File(compressedFilePath)));
        }
        else if(fileType.equalsIgnoreCase("tbz")||fileType.equalsIgnoreCase("bz"))
        {
            is = new TarArchiveInputStream(new BZip2CompressorInputStream(new FileInputStream(new File(compressedFilePath))));
        }
        else if(fileType.equalsIgnoreCase("tgz")||fileType.equalsIgnoreCase("gz"))
        {
            is = new TarArchiveInputStream(new GzipCompressorInputStream(new FileInputStream(new File(compressedFilePath))));
        }
        TarArchiveEntry entry = is.getNextTarEntry();
        extractedFileList = new ArrayList<>();
        while (entry != null) {
            // grab a zip file entry
            String currentEntry = entry.getName();

            if (!entry.isDirectory()) {
                File destFile = new File(Constants.DEFAULT_ZIPOUTPUTPATH, currentEntry);
                File destinationParent = destFile.getParentFile();
                // create the parent directory structure if needed
                destinationParent.mkdirs();
                ArchiveFile archiveFile = new ArchiveFile();
                int currentByte;
                // establish buffer for writing file
                byte data[] = new byte[(int) entry.getSize()];
                // write the current file to disk
                fos = new FileOutputStream(destFile);
                dest = new BufferedOutputStream(fos, (int) entry.getSize());

                // read and write until last byte is encountered
                while ((currentByte = is.read(data, 0, (int) entry.getSize())) != -1) {
                    dest.write(data, 0, currentByte);
                }
                dest.flush();
                dest.close();
                archiveFile.setExtractedFilePath(destFile.getAbsolutePath());
                archiveFile.setFormat(destFile.getName().split("\\.")[1]);
                extractedFileList.add(archiveFile);
                entry = is.getNextTarEntry();
            } else {
                new File(Constants.DEFAULT_ZIPOUTPUTPATH, currentEntry).mkdirs();
                entry = is.getNextTarEntry();
            }

        }
    } catch (IOException e) {
        System.out.println(("ERROR: " + e.getMessage()));
    } catch (Exception e) {
        System.out.println(("ERROR: " + e.getMessage()));
    } finally {
        is.close();
        dest.flush();
        dest.close();
    }

    return extractedFileList;
}

1 Ответ

2 голосов
/ 04 июня 2019

Оригинальный Bzip предположительно использовал запатентованный алгоритм, поэтому Bzip2 родился с использованием алгоритмов и методов, которые не были запатентованы.

Это может быть причиной того, что он больше не используется широко, а библиотеки с открытым исходным кодом игнорируют его.

Существует некоторый код C для распаковки Bzip-файлов, показанный здесь ( gist.github.com mirror ).

Возможно, вы захотите прочитать и переписать это на Java.

...