This post shows how to compress files in Java using Apache Commons Compress, which we can download from Apache Commons.
Compress Files In Java using Zip
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | public static void zipIt() throws Exception { OutputStream out = new FileOutputStream( new File("C:/appl/zip.zip")); ArchiveOutputStream os = new ArchiveStreamFactory() .createArchiveOutputStream("zip", out); os.putArchiveEntry(new ZipArchiveEntry( "testdata/test1.xml")); IOUtils.copy(new FileInputStream( new File("C:/appl/test/1.txt")), os); os.closeArchiveEntry(); os.putArchiveEntry(new ZipArchiveEntry( "testdata/test2.xml")); IOUtils.copy(new FileInputStream( new File("C:/appl/test/1_2.txt")), os); os.closeArchiveEntry(); out.flush(); os.close(); } |
File Compression using Tar
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | public static void tarIt() throws Exception { OutputStream out = new FileOutputStream( new File("C:/appl/zip.tar")); ArchiveOutputStream os = new ArchiveStreamFactory() .createArchiveOutputStream("tar", out); File file1 = new File("C:/appl/test/1.txt"); TarArchiveEntry te1 = new TarArchiveEntry("test/1.txt"); te1.setSize(file1.length()); os.putArchiveEntry(te1); IOUtils.copy(new FileInputStream(file1), os); os.closeArchiveEntry(); File file2 = new File("C:/appl/test/1_2.txt"); TarArchiveEntry te2 = new TarArchiveEntry("test/1_2.txt"); te2.setSize(file2.length()); os.putArchiveEntry(te2); IOUtils.copy(new FileInputStream(file2), os); os.closeArchiveEntry(); out.flush(); os.close(); } |