用java好久了,還沒有寫個壓縮文件的示例,昨晚弄了下,把寫下來,以后可以看。
關系到
java.util.zip.ZipEntry
java.util.zip.ZipOutputStream
如果要解決中文文件名問題,用到ant.jar
這兩個類。
ZipOutputStream.putNextEntry(ZipEntry);就可以了,然后ZipOutputStream.wirte();就得了。
package net.blogjava.chenlb.zip;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
//import java.util.zip.ZipEntry;
//import java.util.zip.ZipOutputStream;
//用ant.jar的zip.*可以解決中文文件名問題
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
/**
* 壓縮文件.
* 2007-10-17 下午11:19:50
* @author chenlb
*/
public class RecursiveZip {
public static void main(String[] args) {
RecursiveZip recursiveZip = new RecursiveZip();
System.out.println("====開始====");
try {
OutputStream os = new FileOutputStream("e:/doc-recursive.zip");
BufferedOutputStream bs = new BufferedOutputStream(os);
ZipOutputStream zo = new ZipOutputStream(bs);
//recursiveZip.zip("e:/recursive-zip/中文文件名.txt", new File("e:/recursive-zip"), zo, true, true);
recursiveZip.zip("e:/recursive-zip", new File("e:/recursive-zip"), zo, true, true);
zo.closeEntry();
zo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("====完成====");
}
/**
* @param path 要壓縮的路徑, 可以是目錄, 也可以是文件.
* @param basePath 如果path是目錄,它一般為new File(path), 作用是:使輸出的zip文件以此目錄為根目錄, 如果為null它只壓縮文件, 不解壓目錄.
* @param zo 壓縮輸出流
* @param isRecursive 是否遞歸
* @param isOutBlankDir 是否輸出空目錄, 要使輸出空目錄為true,同時baseFile不為null.
* @throws IOException
*/
public void zip(String path, File basePath, ZipOutputStream zo, boolean isRecursive, boolean isOutBlankDir) throws IOException {
File inFile = new File(path);
File[] files = new File[0];
if(inFile.isDirectory()) { //是目錄
files = inFile.listFiles();
} else if(inFile.isFile()) { //是文件
files = new File[1];
files[0] = inFile;
}
byte[] buf = new byte[1024];
int len;
//System.out.println("baseFile: "+baseFile.getPath());
for(int i=0; i<files.length; i++) {
String pathName = "";
if(basePath != null) {
if(basePath.isDirectory()) {
pathName = files[i].getPath().substring(basePath.getPath().length()+1);
} else {//文件
pathName = files[i].getPath().substring(basePath.getParent().length()+1);
}
} else {
pathName = files[i].getName();
}
System.out.println(pathName);
if(files[i].isDirectory()) {
if(isOutBlankDir && basePath != null) {
zo.putNextEntry(new ZipEntry(pathName+"/")); //可以使空目錄也放進去
}
if(isRecursive) { //遞歸
zip(files[i].getPath(), basePath, zo, isRecursive, isOutBlankDir);
}
} else {
FileInputStream fin = new FileInputStream(files[i]);
zo.putNextEntry(new ZipEntry(pathName));
while((len=fin.read(buf))>0) {
zo.write(buf,0,len);
}
fin.close();
}
}
}
}
posted on 2007-10-18 13:53
流浪汗 閱讀(3030)
評論(3) 編輯 收藏 所屬分類:
JAVA/J2EE