Package common.util;
Import Java.io.File;
Import Java.io.FileInputStream;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.util.zip.ZipEntry;
Import Java.util.zip.ZipOutputStream;
public class Ziputils {
/** compressing a single file */
public static void ZipFile (string filepath, string zippath) {
String s = Uuid.randomuuid (). toString (); In order to be afraid to delete this temporary file is deleted to the same file
Here filepath the path to the folder to be packaged string filepath = Servletactioncontext.getservletcontext (). Getrealpath ("upload/notice/" +s+ "/");
Zippath the path to the generated zip package string zippath = Servletactioncontext.getservletcontext (). Getrealpath ("upload/notice/" +s+ "/ Week-job.zip "); here's a week-job.zip package.
Servletactioncontext.getservletcontext (). Getrealpath (); Get server address
InputStream input = null;
Zipoutputstream zipout = null;
try {
File File = new file (filepath);
File ZipFile = new file (Zippath);
input = new FileInputStream (file);
ZipOut = new Zipoutputstream (new FileOutputStream (ZipFile));
Zipout.putnextentry (New ZipEntry (File.getname ()));
int temp = 0;
while (temp = Input.read ())! =-1) {
Zipout.write (temp);
}
System.out.println ("Zip" +filepath+ "to" +zippath);
} catch (Exception e) {
E.printstacktrace ();
}finally{
try {
Input.close ();
Zipout.close ();
} catch (IOException e) {
E.printstacktrace ();
}
}
}
/** compress multiple files at once, file in one folder */
public static void Zipmultifile (string filepath, string zippath) {
try {
File File = new file (filepath);//folder to be compressed
File ZipFile = new file (Zippath);
InputStream input = null;
Zipoutputstream zipout = new Zipoutputstream (new FileOutputStream (ZipFile));
if (File.isdirectory ()) {
file[] files = file.listfiles ();
for (int i = 0; i < files.length; ++i) {
input = new FileInputStream (files[i]);
Zipout.putnextentry (New ZipEntry (File.getname () + File.separator + files[i].getname ()));
int temp = 0;
while (temp = Input.read ())! =-1) {
Zipout.write (temp);
}
Input.close ();
}
}else{//Otherwise, the method of compressing a single file is called
ZipFile (filepath, zippath);
}
Zipout.close ();
} catch (Exception e) {
E.printstacktrace ();
}
}
}
Java Build Zip Package