Java Code decompression rar/zip file __java

Source: Internet
Author: User
Tags parent directory rar

Pom.xml

<!--import Zip decompression package-->
<dependency>
    <groupId>ant</groupId>
    <artifactid>ant </artifactId>
    <version>1.6.5</version>
</dependency>
<!--import rar unpack Package-->
<dependency>
    <groupId>com.github.junrar</groupId>
    <artifactid>junrar</ artifactid>
    <version>0.7</version>
</dependency>
Fileunziprar.ziprartofile (filename, uploaddir + "temp\\" + filename, Uploaddir + "\\staticPage")

Fileunziprar.java

Import Org.apache.tools.zip.ZipEntry;
Import Org.apache.tools.zip.ZipFile;
Import java.io.*;
Import java.util.ArrayList;
Import java.util.Enumeration;
Import java.util.List;
Import com.github.junrar.Archive;

Import Com.github.junrar.rarfile.FileHeader; public class Fileunziprar {/** * decompression * * @param sourcefile * @param tofolder * * Public St Atic string Ziprartofile (String fileName, String sourcefile, String tofolder) throws Exception {int pos = Filenam
        E.lastindexof (".");
        String extname = filename.substring (pos + 1). toLowerCase ();
        File Pushfile = new file (sourcefile);
        File Descfile = new file (Tofolder);
        if (!descfile.exists ()) {descfile.mkdirs ();
        //Decompression destination file String Descdir = tofolder + "\" + filename.substring (0, POS) + "\";
        Start extracting zip if (extname.equals ("Zip")) {Fileunziprar.unzipfiles (pushfile, Descdir); else if (extname.equals ("rar")) {
            Start decompression rar fileunziprar.unrarfile (Pushfile.getabsolutepath (), descdir);
        //Verify that the folder contains index.html files, which removes String Linkurl = checkindexhtml (Descdir); if (!
        Stringutil.isnotnullstr (Linkurl)) {throw new Exception ("Missing index.html in file)";
    return linkurl; /** * Check for index.html * * @param strpath * * @return/public static String CHECKINDEXH
        Tml (String strpath) {string linkurl = null;
        list<file> filelist = new arraylist<file> (); list<file> files = getfilelist (filelist, strpath);
                All files in the file directory are placed in the array if (Collectionutil.isnotempty (files)) {for (int i = 0; i < files.size (); i++) {
                String fileName = Files.get (i). GetName ();
                    if ("index.html". Equals (FileName)) {//Determine if there is a index.html String path = Files.get (i). GetPath (); int pos = Path.lastindexof ("UpMall ");
                    Linkurl = path.substring (pos + 7, Path.length ());
                Break
    }} return Linkurl; /** * Get all Files * * @param filelist * @param strpath * @return/public static List
        <File> getfilelist (list<file> filelist, String strpath) {File dir = new File (strpath); file[] files = dir.listfiles (); All files in the file directory are placed in the array if (!= null) {for (int i = 0; i < files.length; i++) {Str
                ing fileName = files[i].getname (); if (Files[i].isdirectory ()) {//Judge is a file or folder Getfilelist (FileList, Files[i].getabsolutepath ());//Get File
                    Absolute path} else {Filelist.add (files[i]);
                Continue
    }} return filelist; /** * Extract to specified directory * * @param zippath * @param descdir *@author */public static void Unzipfiles (String zippath, String descdir) throws IOException {Unzipfiles (
    New File (Zippath), descdir); /** * Extract files to the specified directory * * @param zipfile * @param descdir * @author isea533 * * @Suppres Swarnings ("Rawtypes") public static void Unzipfiles (File zipfile, String descdir) throws IOException {file pa
        Thfile = new File (descdir);
        if (!pathfile.exists ()) {pathfile.mkdirs ();
        } zipfile zip = new ZipFile (ZipFile); For (Enumeration entries = Zip.getentries (); entries.hasmoreelements ();)
            {ZipEntry entry = (zipentry) entries.nextelement ();
            String zipentryname = Entry.getname ();
            InputStream in = Zip.getinputstream (entry);
            String Outpath = (Descdir + zipentryname). ReplaceAll ("\\*", "/");
            ; To determine if a path exists or not, create a file path filename = new file (outpath.substring 0, Outpath.lastindexof ('/')));
            if (!file.exists ()) {file.mkdirs (); 
            //Determine if the file full path is a folder, and if it is uploaded above, do not need to extract the if (new file (Outpath). Isdirectory ()) {continue;

            ///output file path information System.out.println (Outpath);
            OutputStream out = new FileOutputStream (Outpath);
            byte[] buf1 = new byte[1024];
            int Len;
            while (len = In.read (buf1)) > 0) {out.write (buf1, 0, Len);
            } in.close ();
        Out.close ();
     The/** * is extracted to the specified folder according to the original RAR path. * * @param srcrarpath original rar path * @param dstdirectorypath unpacked to the folder * * public static void Unrarfile (S Tring Srcrarpath, String dstdirectorypath) {if (!srcrarpath.tolowercase (). EndsWith (". rar")) {System. OUT.PRINTLN ("Non-RAR file").
            ");
        Return
        } File Dstdiretory = new file (Dstdirectorypath); if (!dstdiretoRy.exists ()) {////when the target directory does not exist, create the folder Dstdiretory.mkdirs ();
        } Archive a = null;
            try {a = new Archive (new File (Srcrarpath));
                if (a!= null) {A.getmainheader (). print ();//print file information.
                Fileheader fh = A.nextfileheader (); while (FH!= null) {if (Fh.isdirectory ()) {//folder File fol = new file (dstdir
                        Ectorypath + File.separator + fh.getfilenamestring ());
                    Fol.mkdirs ();
                                else {//File out = new file (Dstdirectorypath + file.separator
                        + fh.getfilenamestring (). Trim ());
                            try {//The reason to write a try is because if there is an exception in it, it does not affect the continued decompression.
                                    if (!out.exists ()) {if (!out.getparentfile (). exists ()) {//relative path may be multilevel, you may need to create a parent directory. Out.getparentfiLe (). Mkdirs ();
                            } out.createnewfile ();
                            } fileoutputstream OS = new FileOutputStream (out);
                            A.extractfile (FH, OS);
                        Os.close ();
                        catch (Exception ex) {ex.printstacktrace ();
                } FH = A.nextfileheader ();
            } a.close ();
        } catch (Exception e) {e.printstacktrace ();
 }
    }

}


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.