Category Archives: archiving

Tar a directory preserving structure with Apache in java

How can i tar a directory and preserve the directory structure using the org.apache.commons.compress libraries?

With what i am doing below, i am just getting a package that has everything flattened.

Thanks!


Here is what i have been trying and it is not working.

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;
}