Code:
Copy Code code as follows:
Import Java.io.BufferedOutputStream;
Import Java.io.File;
Import Java.io.FileInputStream;
Import Java.io.FileOutputStream;
Import Org.apache.tools.zip.ZipEntry;
Import Org.apache.tools.zip.ZipOutputStream;
/**
* @project: Test
* @author Chenssy
* @date 2013-7-28
* @Description: File Compression Tool class
* Compress the specified files/folders into zip, rar compressed files
*/
public class Compressedfileutil {
/**
* Default constructor
*/
Public Compressedfileutil () {
}
/**
* @desc the source files/folders to generate compressed files in the specified format, zip format
* @param resourepath source files/folders
* @param targetpath Destination Compressed file save path
* @return void
* @throws Exception
*/
public void Compressedfile (String resourcespath,string TargetPath) throws exception{
File Resourcesfile = new file (Resourcespath); source files
File TargetFile = new file (TargetPath); Objective
If the destination path does not exist, the new
if (!targetfile.exists ()) {
Targetfile.mkdirs ();
}
String targetName = resourcesfile.getname () + ". zip"; Destination Compressed file name
FileOutputStream outputstream = new FileOutputStream (targetpath+ "\" +targetname);
Zipoutputstream out = new Zipoutputstream (new Bufferedoutputstream (OutputStream));
Createcompressedfile (out, Resourcesfile, "");
Out.close ();
}
/**
* @desc generate compressed files.
* If a folder, then use recursion, file traversal, compression
* If it is a file, compress directly
* @param out output stream
* @param file Destination files
* @return void
* @throws Exception
*/
public void Createcompressedfile (Zipoutputstream out,file file,string dir) throws exception{
If the current folder is present, further processing is done
if (File.isdirectory ()) {
Get file list information
file[] files = file.listfiles ();
To add a folder to the next-level package directory
Out.putnextentry (New ZipEntry (dir+ "/"));
dir = dir.length () = = 0? "": Dir + "/";
To wrap a file in a folder
for (int i = 0; i < files.length; i++) {
Createcompressedfile (out, files[i], dir + files[i].getname ()); Recursive processing
}
}
else{//Current is file, package processing
File input stream
FileInputStream fis = new FileInputStream (file);
Out.putnextentry (New ZipEntry (dir));
Write operation
int j = 0;
byte[] buffer = new byte[1024];
while ((j = fis.read (buffer)) > 0) {
Out.write (BUFFER,0,J);
}
Close the input stream
Fis.close ();
}
}
public static void Main (string[] args) {
Compressedfileutil compressedfileutil = new Compressedfileutil ();
try {
Compressedfileutil.compressedfile ("G:\\zip", "F:\\zip");
SYSTEM.OUT.PRINTLN ("Compressed files have been generated ...");
catch (Exception e) {
SYSTEM.OUT.PRINTLN ("Compressed file generation failed ...");
E.printstacktrace ();
}
}
}