Java decompression. zip,. tar.gz,. tar.bz2 (Support Chinese)

Source: Internet
Author: User
Tags create directory decompress file

This article describes the way Java unzip. zip,. tar.gz,. tar.bz2.

    1. For zip files: use java.util.zip.ZipEntry and java.util.zip.ZipFile , by setting Charset to StandardCharsets.UTF_8 support Chinese.
    2. For. tar.gz, tgz files: You can consider packing with tar first and then using GZ for compression. Use commons-compress the and of the package TarArchiveInputStream GzipCompressorInputStream .
    3. For. tar.bz2 files: You can consider packing with tar first and then compressing with bz2. Use commons-compress the and of the package TarArchiveInputStream BZip2CompressorInputStream .

There is a problem here if you use a TarInputStream jdk with a mix of GZIPInputStream garbled. And the use commons-compress of the package TarArchiveInputStream GzipCompressorInputStream can solve the garbled problem.

The code is as follows:

public class Ziputil {private static final Logger LOG = Loggerfactory.getlogger (Ziputil.class);    private static final int buffer_size = 1024 * 100;        Private Ziputil () {} public static Boolean decompress (string FilePath, String OutputDir, Boolean isDeleted) {        File File = new file (FilePath);            if (!file.exists ()) {log.error ("decompress file not exist.");        return false;            } try {if (Filepath.endswith (". zip")) {UnZip (file, OutputDir); } if (Filepath.endswith (". tar.gz") | | | Filepath.endswith (". tgz")) {decompresstargz (file, Outputd            IR);            } if (Filepath.endswith (". tar.bz2")) {decompressTarBz2 (file, OutputDir);            } filterfile (New File (OutputDir));            if (isDeleted) {fileutils.deletequietly (file);        } return true; } catch (IOException e) {log.error ("DecoMpress occur error. ");}    return false; /** * Unzip the. zip file * * @param file to extract the zip file object * @param outputDir to extract to a specified directory * @throws ioexc Eption */public static void UnZip (file file, String OutputDir) throws IOException {try (ZipFile ZipFile =            New ZipFile (file, standardcharsets.utf_8)) {//Create output directory CreateDirectory (outputDir, NULL);            Enumeration<?> enums = Zipfile.entries ();                while (Enums.hasmoreelements ()) {ZipEntry entry = (zipentry) enums.nextelement ();                if (Entry.isdirectory ()) {//Create empty directory CreateDirectory (OutputDir, Entry.getname ()); } else {try (InputStream in = Zipfile.getinputstream (entry)) {try (OutputStream out = new FileOutputStream (new File (OutputDir + file.separator + Entry.getna Me ())) {WritefIle (in, out);  }}}}} public static void Decompresstargz (file file, String OutputDir) throws IOException {try (tararchiveinputstream Tarin = new Tararchiveinputstream (New G Zipcompressorinputstream (New Bufferedinputstream (New Fileinputstre            AM (file))) {//Create output directory CreateDirectory (outputDir, NULL);            Tararchiveentry entry = null;                    while ((entry = Tarin.getnexttarentry ()) = null) {//Is the directory if (Entry.isdirectory ()) {                Create an empty directory CreateDirectory (OutputDir, Entry.getname ());                            } else {//is a file try (outputstream out = new FileOutputStream (              New File (OutputDir + file.separator + entry.getname ()))) {WriteFile (Tarin, out);      }}}}}/** * Unzip tar.bz2 file * * @param file archive * @pa        Ram OutputDir Destination Folder */public static void decompressTarBz2 (file file, String OutputDir) throws IOException { Try (tararchiveinputstream Tarin = new Tararchiveinputstream (New Bzip2co Mpressorinputstream (new FileInputStream (file))) {CreateDirectory (OUTPUTD            IR, NULL);            Tararchiveentry entry; while ((entry = Tarin.getnexttarentry ()) = null) {if (Entry.isdirectory ()) {Createdir                Ectory (OutputDir, Entry.getname ()); } else {try (outputstream out = new FileOutputStream (The new File (OutputDir +                    File.separator + entry.getname ())) {WriteFile (Tarin, out); }                }            }        }    }    /**     * Write file * * @param in * @param out * @throws IOException */public static void WriteFile (InputStream i        N, OutputStream out) throws IOException {int length;        Byte[] B = new Byte[buffer_size];        while (length = In.read (b))! =-1) {out.write (b, 0, length); }}/** * Create directory * * @param outputDir * @param subdir * * public static void CreateDirectory (STR        ing OutputDir, String subdir) {File File = new file (OutputDir); The subdirectory is not empty if (! ( SubDir = = NULL | |        Subdir.trim (). Equals (""))) {file = new file (OutputDir + file.separator + subdir); } if (!file.exists ()) {if (!file.getparentfile (). exists ()) {File.getparentfile (). mkdirs            ();        } file.mkdirs (); }}/** * Remove Mac compression and unzip the resulting __macosx folder and the. Other files that begin with. * @param filteredfile */public static void filt Erfile (File filteredfile) {if (filteredfile! = null) {file[] files = filteredfile.listfiles ();                        for (File file:files) {if (File.getname (). StartsWith (".") | | (File.isdirectory () && file.getname (). Equals ("__macosx")))                {fileutils.deletequietly (file); }            }        }    }}

Code address

reference Documentation :

    1. Commons-compress Official Example

Java decompression. zip,. tar.gz,. tar.bz2 (Support Chinese)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.