I am looking to create a .tar.gz file of the following folder/directory structure, while retaining the same folder/ directory structure
ParentDir\
ChildDir1\
-file1
ChildDir2\
-file2
-file3
ChildDir3\
-file4
-file5
However I am only able to create a .tar.gz of all the files, without the folder/directory structure. ie: ParentDir.tar.gz
ParentDir\
-file1
-file2
-file3
-file4
-file5
Using the user accepted answer in Compress directory to tar.gz with Commons Compress, I have the following code:
public void exportStaticFilesTar(String appID) throws, Exception {
FileOutputStream fOut = null;
BufferedOutputStream bOut = null;
GzipCompressorOutputStream gzOut = null;
TarArchiveOutputStream tOut = null;
try {
String filename = "ParentDir.tar.gz"
//"parent/childDirToCompress/"
String path = "<path to ParentDir>";
fOut = new FileOutputStream(new File(filename));
bOut = new BufferedOutputStream(fOut);
gzOut = new GzipCompressorOutputStream(bOut);
tOut = new TarArchiveOutputStream(gzOut);
addFileToTarGz(tOut, path, "");
} catch (Exception e) {
log.error("Error creating .tar.gz: " +e);
} finally {
tOut.finish();
tOut.close();
gzOut.close();
bOut.close();
fOut.close();
}
//Download the file locally
}
private void addFileToTarGz(TarArchiveOutputStream tOut, String path, String base) throws IOException {
File f = new File(path);
String entryName = base + f.getName();
TarArchiveEntry tarEntry = new TarArchiveEntry(f, entryName);
tOut.putArchiveEntry(tarEntry);
if (f.isFile()) {
IOUtils.copy(new FileInputStream(f), tOut);
tOut.closeArchiveEntry();
} else {
tOut.closeArchiveEntry();
File[] children = f.listFiles();
if (children != null) {
for (File child : children) {
addFileToTarGz(tOut, child.getAbsolutePath(), entryName + "/");
}
}
}
}
Can someone please advice, how I can modify the current code to retain the folder/directory structure when creating a .tar.gz file. Thanks!