Tar structure of persisting directory with Apache in java

How can I tar

create a directory and keep the directory structure using libraries org.apache.commons.compress

?

With what I do below, I just get a package that has everything flattened.

Thank!


Here is what I tried and doesn't work.

public static void createTar(final String tarName, final List<File> pathEntries) throws IOException {
    OutputStream tarOutput = new FileOutputStream(new File(tarName));

    ArchiveOutputStream tarArchive = new TarArchiveOutputStream(tarOutput);

    List<File> files = new ArrayList<File>();

    for (File file : pathEntries) {
        files.addAll(recurseDirectory(file));
    }

    for (File file : files) {

        TarArchiveEntry tarArchiveEntry = new TarArchiveEntry(file, file.getName());
        tarArchiveEntry.setSize(file.length());
        tarArchive.putArchiveEntry(tarArchiveEntry);
        FileInputStream fileInputStream = new FileInputStream(file);
        IOUtils.copy(fileInputStream, tarArchive);
        fileInputStream.close();
        tarArchive.closeArchiveEntry();
    }

    tarArchive.finish();
    tarOutput.close();
}

public static List<File> recurseDirectory(final File directory) {

    List<File> files = new ArrayList<File>();

    if (directory != null && directory.isDirectory()) {

        for (File file : directory.listFiles()) {

            if (file.isDirectory()) {
                files.addAll(recurseDirectory(file));
            } else {
                files.add(file);
            }
        }
    }

    return files;
}

      

+3


source to share


1 answer


Your problem is here:

TarArchiveEntry tarArchiveEntry = new TarArchiveEntry(file, file.getName());

      



Because you put each file with only its name, not its path, in tar.

You need to pass the relative path from your path entries to this file instead file.getName()

.

+2


source







All Articles