2

我正在使用 Apache Commons Compress 创建 tar 存档并解压缩它们。我的问题始于这种方法:

    private void decompressFile(File file) throws IOException {
    logger.info("Decompressing " + file.getName());

    BufferedOutputStream outputStream = null;
    TarArchiveInputStream tarInputStream = null;

    try {
        tarInputStream = new TarArchiveInputStream(
                new FileInputStream(file));

        TarArchiveEntry entry;
        while ((entry = tarInputStream.getNextTarEntry()) != null) {
            if (!entry.isDirectory()) {
                File compressedFile = entry.getFile();
                File tempFile = File.createTempFile(
                        compressedFile.getName(), "");

                byte[] buffer = new byte[BUFFER_MAX_SIZE];
                outputStream = new BufferedOutputStream(
                        new FileOutputStream(tempFile), BUFFER_MAX_SIZE);

                int count = 0;
                while ((count = tarInputStream.read(buffer, 0, BUFFER_MAX_SIZE)) != -1) {
                    outputStream.write(buffer, 0, count);
                }
            }

            deleteFile(file);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (outputStream != null) {
            outputStream.flush();
            outputStream.close();
        }
    }
}

每次我运行代码时,compressedFile 变量为空,但 while 循环正在遍历我的测试 tar 中的所有条目。

你能帮我理解我做错了什么吗?

4

2 回答 2

4

从官方文档
阅读 tar 档案中的条目:

    TarArchiveEntry entry = tarInput.getNextTarEntry();
    byte[] content = new byte[entry.getSize()];
    LOOP UNTIL entry.getSize() HAS BEEN READ {
        tarInput.read(content, offset, content.length - offset);
    }

我已经从您的实现开始编写了一个示例,并使用非常简单的 .tar 进行了测试(只有一个文本条目)。
不知道确切的要求,我只是负责解决读取存档的问题,避免使用空指针。调试中,该条目可用,您也发现了

    private static void decompressFile(File file) throws IOException {

        BufferedOutputStream outputStream = null;
        TarArchiveInputStream tarInputStream = null;

        try {
            tarInputStream = new TarArchiveInputStream(
                new FileInputStream(file));

            TarArchiveEntry entry;
            while ((entry = tarInputStream.getNextTarEntry()) != null) {
                if (!entry.isDirectory()) {
                    File compressedFile = entry.getFile();
                    String name = entry.getName();

                    int size = 0;
                    int c;
                    while (size < entry.getSize()) {
                        c = tarInputStream.read();
                        System.out.print((char) c);
                        size++;
                }
    (.......)

正如我所说:我使用仅包含一个文本条目的 tar 进行了测试(您也可以尝试这种方法来验证代码)以确保避免 null。
您需要根据您的实际需求进行所有必要的调整。很明显,您必须像我在顶部发布的元代码中那样处理流。
它显示了如何处理单个条目。

于 2013-09-01T20:05:02.083 回答
3

尝试使用getNextEntry( )方法而不是getNextTarEntry()方法。

第二种方法返回一个 TarArchiveEntry。可能这不是你想要的!

于 2013-09-01T13:53:49.783 回答