The directory structure is as follows:
Import Java.io.file;import java.io.fileinputstream;import java.io.fileoutputstream;import java.io.IOException; Import Java.nio.file.path;import Java.nio.file.paths;import Java.util.zip.zipentry;import Java.util.zip.zipinputstream;import Java.util.zip.zipoutputstream;public class Zipdemo {public static void main (Strin G[] Args {try {//zipfolder ("/home/hadoop/test";); Unzip ("/home/hadoop/mytest/test.zip", "/home/hadoop/mytest/"); } catch (IOException e) {e.printstacktrace (); }} static void Zipfolder (String _path) throws IOException {path Path = Paths.get (_path); String target = "/home/hadoop/mytest/test.zip"; String target = path.getparent () + "/" + path.getfilename () + ". zip"; /* SYSTEM.OUT.PRINTLN (Path.getfilename ()); System.out.println (Path.getroot ()); System.out.println (Path.getparent ()); SYSTEM.OUT.PRINTLN (target); */Zipoutputstream Zo = new Zipoutputstream (New FileoUtputstream (target)); ZipFile (Zo,path, ""); Zo.close (); } static void ZipFile (Zipoutputstream zo,path _path,string parentpath) throws IOException {File _file = _pat H.tofile (); if (_file.isfile ()) {byte[] buff = new byte[1024]; FileInputStream fi = new FileInputStream (_file); int Len; Zo.putnextentry (New ZipEntry (Parentpath + "/" + _file.getname ())); while (Len=fi.read (buff)) >0) zo.write (buff, 0, Len); Zo.closeentry (); Fi.close (); } if (_file.isdirectory ()) {if (_file.listfiles (). length==0) {Zo.putnex Tentry (New ZipEntry (Parentpath.equals (")") _file.getname ():p Arentpath + "/" + _file.getname () + "/")); } for (File __file: _file.listfiles ()) ZipFile (Zo,__file.topath (), Parentpath.equals ("")? _file.ge Tname ():p arentpath+ "/" + _file.getname ()); }} Static void Unzip (String path,string target) throws IOException {file TargetFolder = new File (target); Zipinputstream zi = new Zipinputstream (new FileInputStream (path)); ZipEntry ze = null; FileOutputStream fo = null; byte[] buff = new byte[1024]; int Len; while ((Ze = zi.getnextentry ())!=null) {File _file = new File (Targetfolder,ze.getname ()); if (!_file.getparentfile (). exists ()) _file.getparentfile (). Mkdirs (); if (Ze.isdirectory ()) {_file.mkdir (); } else//file {fo = new FileOutputStream (_file); while (Len=zi.read (buff)) >0) fo.write (buff, 0, Len); Fo.close (); } zi.closeentry (); } zi.close (); }}
Java Zip and Unzip demo