Java implementation of compressed and uncompressed files

Source: Internet
Author: User

Due to the need to unzip the zip file, the investigation found that there are two open source Toolkit, one is the Apache Ant Toolkit, the other is the Java API comes with the toolkit However, there is a problem with the toolkit that comes with Java: if there are non-English characters (such as Chinese, Israeli) in the compressed or decompressed file, there will be a problem during the operation: Malformal eception ...

Here is the code for compression and decompression via Apache's Zip toolkit (requires Ant.jar):

Package Com.steven.file;import Java.io.file;import Java.io.fileinputstream;import java.io.FileNotFoundException; Import Java.io.fileoutputstream;import java.io.ioexception;import java.io.inputstream;import java.io.OutputStream; Import Java.util.arraylist;import java.util.enumeration;import Java.util.list;import org.apache.tools.zip.ZipEntry ; Import org.apache.tools.zip.zipfile;import org.apache.tools.zip.zipoutputstream;/** * Compress or unzip zip: * Due to the use of classes under the Java.util.zip Toolkit, there is a problem with Chinese garbled, so use the tool class under Org.apache.tools.zip in Ant.jar * @author Administrator */public class Ziputil {/** * compressed file or path * @param zip compression for destination address * @param srcfiles Compressed source file */public static void ZipF Ile (String zip, list<file> srcfiles) {try {if (Zip.endswith (". zip") | | zip.endswith (".                Zip ")) {Zipoutputstream _zipout = new Zipoutputstream (new FileOutputStream (new File (Zip)));                _zipout.setencoding ("GBK");                  for (File _f:srcfiles) {  Handlerfile (Zip, _zipout, _f, "");            } _zipout.close ();            }else{System.out.println ("target file[" + Zip + "] is not. zip type file");  }} catch (FileNotFoundException e) {} catch (IOException e) {}}/** * * @param     Zip compression for the destination address * @param zipout * @param srcfile Compressed file information * @param path in zip relative paths * @throws IOException */private static void Handlerfile (String zip, Zipoutputstream zipout, File srcfile, String path) throws Ioexcep        tion{System.out.println ("Begin to compression file[" + srcfile.getname () + "]"); if (! "". Equals (path) &&!        Path.endswith (file.separator)) {path + = File.separator; } if (! Srcfile.getpath (). Equals (Zip)) {if (Srcfile.isdirectory ()) {file[] _files = src                File.listfiles (); if (_files.length = = 0) {zipout.putnextentry (newZipEntry (path + srcfile.getname () + file.separator));                Zipout.closeentry (); }else{for (File _f: _files) {handlerfile (zip, zipout, _f, path + srcfile.g                    Etname ());                }}}else{byte[] _byte = new byte[1024];                InputStream _in = new FileInputStream (srcfile);                Zipout.putnextentry (New ZipEntry (path + srcfile.getname ()));                 int len = 0;                while (len = _in.read (_byte)) > 0) {zipout.write (_byte, 0, Len);                } _in.close ();            Zipout.closeentry (); }}}/** * Unzip the zip file, unzip the contents of the zip file into the TARGETDIR directory * @param zippath the zip file name to be unzipped * @param descdir Target Record */public static list<file> Upzipfile (String zippath, String descdir) {return upzipfile (new File (Z    Ippath), Descdir); }/** * Yes.ZIP file to extract * @param zipfile unzip the file * @param the target address of descdir compression, such as: d:\\ test or/mnt/d/Test * * @return */@Suppres Swarnings ("Rawtypes") public static list<file> Upzipfile (File zipfile, String descdir) {list<file>        _list = new arraylist<file> ();            try {zipfile _zipfile = new ZipFile (ZipFile, "GBK"); For (Enumeration entries = _zipfile.getentries (); entries.hasmoreelements ();)                {ZipEntry entry = (zipentry) entries.nextelement ();                File _file = new file (Descdir + file.separator + entry.getname ());                if (Entry.isdirectory ()) {_file.mkdirs ();                    }else{byte[] _byte = new byte[1024];                    File _parent = _file.getparentfile ();                    if (!_parent.exists ()) {_parent.mkdirs ();                    } InputStream _in = _zipfile.getinputstream (entry); OuTputstream _out = new FileOutputStream (_file);                    int len = 0;                    while (len = _in.read (_byte)) > 0) {_out.write (_byte, 0, Len);                     } _in.close ();                    _out.flush ();                    _out.close ();                _list.add (_file);    }}} catch (IOException e) {} return _list;            /** * Delete files under temporary generated folders and folders */public static void DeleteFile (String delpath) {try {            File File = new file (Delpath);            if (!file.isdirectory ()) {file.delete ();                } else if (File.isdirectory ()) {string[] filelist = File.list (); for (int i = 0; i < filelist.length; i++) {File Delfile = new File (Delpath + file.separator + filel                    Ist[i]);      if (!delfile.isdirectory ()) {delfile.delete ();              } else if (Delfile.isdirectory ()) {DeleteFile (Delpath + file.separator + filelist[i]                    );            }} file.delete ();        }} catch (Exception e) {e.printstacktrace ();    }} public static void Main (string[] args) {upzipfile ("Steven.zip", "d://test"); }    }

The following is the code for the implementation of the compression and decompression toolkit implemented in the Java API under the Java.util.zip package (if the file name has a non-English encoding, there is a problem):

Package Testzip;import Java.io.file;import Java.io.fileoutputstream;import java.io.ioexception;import Java.io.inputstream;import Java.io.outputstream;import Java.util.enumeration;import Java.util.zip.ZipEntry;import            Java.util.zip.zipfile;import Org.apache.commons.io.ioutils;public class Ziptest {/** * Unzip it * * @param zipfile * Input zip file * @param output * Zip file output folder * @throws IOException */public static void UnZip  It (string file, String OutputFolder) throws IOException {ZipFile zipfile = new ZipFile (file); try {enumeration<? extends zipentry> entries = Zipfile.entries (); while (Entries.hasmoreelements ()) {ZipEntry entry = entries.nextelement (); File Entrydestination = new file (OutputFolder, Entry.getname ()), if (Entry.isdirectory ()) {entrydestination.mkdirs ();} else {entrydestination.getparentfile (). Mkdirs (); InputStream in = Zipfile.getinputstream (entry); OutputStream out = new FileOutputStream (entrydestination); Ioutils.copy (in, out); ioutils.clOsequietly (in); Out.close ();}}} finally {zipfile.close ();}} public static void Main (string[] args) throws Exception {Unzipit ("Test.zip", "D://test");}}

  

Java implementation of compressed and uncompressed files

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.