Java about the processing of compressed packets, I posted here three-format (Zip,rar,tar) decompression method (currently only used to extract, so compression too much research).

Source: Internet
Author: User

1, first of all, we first say why there are three formats:

(1) RAR format: RAR format is the first compression method, it is mainly used for the compression of some files of commercial organizations, it can be based on the requirements of different companies, to set up different compression algorithms, this algorithm is not public, security is relatively high, but he is charged.

(2) Zip format: Because of the RAR format charges, will inevitably be born some free compression format, then zip is born in such circumstances. The same compression algorithm is also public, no charge, the effect of course is slightly worse than the RAR format.

(3) Tar format: Tar is a free compression format introduced domestically.

2, Java Programming implementation of the Rar,zip,tar format of decompression.

(1) RAR decompression: Here you need to use the Junrar-0.7.jar package, here is: Http://pan.baidu.com/s/1mg80F1I

/*** * Extract RAR files * <p> description </p> * @date 2014-7-16 1:59:28 *@version*@paramSourcerar *@paramDestDir *@throwsException*/PublicStaticvoidUnRar (String Sourcerar, String destDir)ThrowsException {Archive A =Null; FileOutputStream fos =Null;Try{a =New Archive (NewFile (Sourcerar)); Fileheader fh =A.nextfileheader ();while (FH! =Null) {if (!Fh.isdirectory ()) {//1 according to different operating systems get the corresponding destDirName and destfilename String compressfilename =Fh.getfilenamew (). Trim (); String destFileName = ""; String destdirname = "";//Non-Windows systemsif (File.separator.equals ("/") {destFileName = DestDir + "//" + Compressfilename.replaceall ("\\\\", "/"); destDirName = destfilename.substring (0, Destfilename.lastindexof ("/"));//Windows System}Else{destfilename = destdir+ "//" + Compressfilename.replaceall ("/", "\\\\"); destDirName = destfilename.substring (0,destfilename.lastindexof ("\ \")); }//2 Creating a folder file Dir =NewFile (destDirName);if (!dir.exists () | | |!Dir.isdirectory ()) {dir.mkdirs ();}//3 Unzip the file FOS =New FileOutputStream (NewFile (destFileName)); A.extractfile (FH, FOS); Fos.close (); FOS =Null; } FH =A.nextfileheader (); } a.close (); A =Null; }Catch(Exception e) {Log.error ("The Methord UnRar is Fiail", e);throw new Exception ("RAR format decompression failed! ");} finally {try {if (fos! = nullnullif (A! = nullnullcatch (Exception e) {log.error ("the Methord UnRar close Is Fiail "          

(2) Zip decompression: This comes directly with Apache.

/*** Unzip the zip file to extract the contents of the zip file into the descfilename directory *@paramZipfilename zip file required for decompression *@paramDescfilename target file*/PublicStaticBooleanUnzipfiles (String zipfilename, String descfilename) {String descfilenames =Descfilename;if (!Descfilenames.endswith (File.separator)) {descfilenames = Descfilenames +File.separator; }Try{//Create a ZipFile object based on a zip file ZipFile zipfile =New ZipFile (New File (Zipfilename), "GB2312");//2014/6/27 Extract garbled Lynn Yang Modify ZipEntry entry =Null; String EntryName =Null; String Descfiledir =Null;byte[] buf =Newbyte[4096];int readbyte = 0;//Get all the entry @SuppressWarnings in the zip file ("Rawtypes") Enumeration enums =Zipfile.getentries ();//Traverse All EntryWhile(Enums.hasmoreelements ()) {entry =(ZipEntry) enums.nextelement ();//Get entry's name EntryName =Entry.getname (); Descfiledir = Descfilenames +EntryName;If(Entry.isdirectory ()) {//If entry is a directory, create a directoryNewFile (Descfiledir). Mkdirs ();Continue; }Else{//If entry is a file, the parent directory is createdNewFile (Descfiledir). Getparentfile (). Mkdirs (); } File File =NewFile (Descfiledir);//Open file output stream OutputStream OS =new FileOutputStream (file); // Zipfile.getinputstream (entry); while ((ReadByte = Is.read (BUF))! = -1) {Os.write (buf, 0< Span style= "color: #000000;" >, ReadByte); } os.close (); Is.close (); } zipfile.close (); // Log.debug ("file extraction succeeded!"); return truecatch (Exception e) {e.printstacktrace (); return false  

(2) Tar decompression: The Java-gnu-tar-0.0.1.jar package is needed here: Http://pan.baidu.com/s/1sjCuquT

/*** Unzip the Tar file * Description * <p> Description </p> * @date 2014-7-16 2:00:30 *@version*@paramPath*/PublicStaticvoid Untar (String path,string DestDir)ThrowsException {InputStream InputStream =Null; OutputStream OutputStream =Null; Tarinputstream ZiS =Null;Try{InputStream =New FileInputStream (NewFile (path)); ZiS =NewTarinputstream (InputStream);//Compressed package tarentry, there are multiple files (including folders) on how many tarentry tarentry tarentry =Null; String destFileName = ""; String destdirname = "";while ((Tarentry = Zis.getnextentry ())! =Null{destfilename = destdir+ "\ \" + Tarentry.getname (). ReplaceAll ("/", "\\\\");//Get file Address destDirName = destfilename.substring (0,destfilename.lastindexof ("\ \"));//Get files directory File Dir =NewFile (destDirName);if (!dir.exists () | | |!Dir.isdirectory ()) {dir.mkdirs ();}//Determine if the directoryif (!destfilename.substring (0, Destfilename.length ()-1). Equals (destDirName)) {outputstream =New FileOutputStream (NewFile (destFileName));//A cache pool can be sized to fit the situation (it turns out to be useful)byte[] Buffer =Newbyte[1024 * 100];while (True) {int readsize =Zis.read (buffer); Outputstream.write (buffer);if (ReadSize < 1024 * 50) {Break; } } } } }Catch(IOException e) {Log.error ("The Methord Untar is Fiail", e);throw new Exception ("Tar format decompression failed!) ");} finally {try {if (Outputstream!=null if (Inputstream!=null ) Inputstream.close (); if (Zis!=null) Zis.close (); } catch (Exception e) {log.error ("the Methord Untar close Is Fiail "         

The tar decompression has the Chinese garbled, has not found the suitable treatment method, very sorry if has the good office please reminds me.

Reproduced self-flapping ball kitten (blog Park)

Java about the processing of compressed packets, I posted here three-format (Zip,rar,tar) decompression method (currently only used to extract, so compression too much research).

Related Article

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.