prolink007
prolink007

Reputation: 34544

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

Upvotes: 4

Views: 3858

Answers (2)

John kerich
John kerich

Reputation: 46

The library has a character limit of 100 characters if you are doing full directory path to the file. You need to modify TarArchiveOutputStream for long paths. Then it works.

TarArchiveOutputStream tOut = new TarArchiveOutputStream(gzOut)) 
// set format to posix so it handles long file name paths
tOut.setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX);

Upvotes: 0

MByD
MByD

Reputation: 137322

Your problem is here:

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

Because you put each file with only it's name, not his path, in the tar.

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

Upvotes: 4

Related Questions