I want to use Java to compress a folder to a tar file (in programmatic way). I think there must be an open source or library to do it. However, I cannot find such method.
Alternatively, could I make a zip file and rename its extended name as .tar?
Anyone could suggest a library to do it? Thanks!
.tar
archive files are not compressed. You have to run a file compression on it like gzip and turn it into something like.tar.gz
.If you just want to just archive a directory, take a look at:
I would look at Apache Commons Compress.
There is an example part way down this examples page, which shows off a tar example.
You can use the jtar - Java Tar library.
Taken from their site:
An example, also from their site:
I have produced following code to solve this problem. This code checks if any of files to be incorporated already exist in tar file and updates that entry. Later if it doesn't exist append to the end of archive.
If you use Gradle use following dependency:
I also tried org.xeustechnologies:jtar:1.1 but performance is way below the one provided by org.apache.commons:commons-compress:1.12
Notes about performance using different implementations:
Zipping 10 times using Java 1.8 zip:
- java.util.zip.ZipEntry;
- java.util.zip.ZipInputStream;
- java.util.zip.ZipOutputStream;
[2016-07-19 19:13:11] Before
[2016-07-19 19:13:18] After
7 seconds
Tar-ing 10 times using jtar:
- org.xeustechnologies.jtar.TarEntry;
- org.xeustechnologies.jtar.TarInputStream;
- org.xeustechnologies.jtar.TarOutputStream;
[2016-07-19 19:21:23] Before
[2016-07-19 19:25:18] After
3m55sec
shell call to Cygwin /usr/bin/tar - 10 times
[2016-07-19 19:33:04] Before
[2016-07-19 19:33:14] After
14 seconds
Tar-ing 100(hundred) times using org.apache.commons.compress:
- org.apache.commons.compress.archivers.ArchiveEntry;
- org.apache.commons.compress.archivers.tar.TarArchiveEntry;
- org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
- org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
[2016-07-19 23:04:45] Before
[2016-07-19 23:04:48] After
3 seconds
Tar-ing 1000(thousand) times using org.apache.commons.compress:
[2016-07-19 23:10:28] Before
[2016-07-19 23:10:48] After
20 seconds