Need to write a file compression program in Java, First prepared to use the Java library in the Java.util.zip.ZipOutputStream, but a search, found that there is a problem with Chinese garbled, so the use of org.apache.tools.zip.ZipOutputStream.
Because of the code built with the MAVEN2, it's convenient to look for a package and download the latest Ant-1.8.1.jar package. During the reference to a piece of article, but the address can not find. Nonsense not much to say, on the code.
Class Zipcompressor
Import Java.io.BufferedInputStream;
Import Java.io.File;
Import Java.io.FileInputStream;
Import Java.io.FileOutputStream;
Import java.util.zip.CRC32;
Import Java.util.zip.CheckedOutputStream;
Import Org.apache.tools.zip.ZipEntry;
Import Org.apache.tools.zip.ZipOutputStream;
public class Zipcompressor {
static final int BUFFER = 8192;
Private File ZipFile;
Public Zipcompressor (String pathName) {
ZipFile = new File (pathName);
}
/**
* Compress files
* @param srcpathname
*/
public void compress (String srcpathname) {
File File = new file (srcpathname);
if (!file.exists ())
throw new RuntimeException (Srcpathname + "does not exist.) ");
try {
FileOutputStream FileOutputStream = new FileOutputStream (ZipFile);
Checkedoutputstream cos = new Checkedoutputstream (FileOutputStream,
New CRC32 ()); Without CRC32, you can generate files as well. About the data how to check, please expert advice
Zipoutputstream out = new Zipoutputstream (COS);
Out.setencoding ("GBK"); If you do not add this sentence, the compressed file can still be generated, but in the open and decompression, will display garbled, but will still be extracted
String basedir = "";
Compress (file, out, basedir);
Out.close ();
catch (Exception e) {
throw new RuntimeException (e);
}
}
private void compress (file file, zipoutputstream out, String basedir) {
/* Determine whether the directory or file * *
if (File.isdirectory ()) {
This.compressdirectory (file, out, basedir);
} else {
This.compressfile (file, out, basedir);
}
}
/** Compress a directory * *
private void Compressdirectory (File dir, zipoutputstream out, String basedir) {
if (!dir.exists ())
Return
file[] files = dir.listfiles ();
for (int i = 0; i < files.length; i++) {
/* Recursive * *
Compress (Files[i], out, Basedir + dir.getname () + "/");
}
}
/** Compress a file * *
private void Compressfile (file file, zipoutputstream out, String basedir) {
if (!file.exists ()) {
Return
}
try {
Bufferedinputstream bis = new Bufferedinputstream (
New FileInputStream (file));
ZipEntry entry = new ZipEntry (Basedir + file.getname ());
Out.putnextentry (entry);
int count;
byte data[] = new Byte[buffer];
while (count = bis.read (data, 0, BUFFER)!=-1) {
Out.write (data, 0, count);
}
Bis.close ();
catch (Exception e) {
throw new RuntimeException (e);
}
}
public static void Main (string[] args) {
Zipcompressor ZC = new Zipcompressor ("e://folder. zip");
Zc.compress ("e://folder Test"); Compress a folder
}
}