import java.io.File
import org.apache.tools.zip.ZipOutputStream//扰哪孝这个包在ant.jar里,要到官方网下载
import java.io.FileInputStream
import java.io.FileOutputStream
import java.util.zip.ZipInputStream
import java.util.zip.ZipEntry
public class CompressBook {
public CompressBook() {}
/*
* inputFileName 输入一个文件夹
* zipFileName 输出一个压缩文件夹
*/
public void zip(String inputFileName) throws Exception {
String zipFileName = "c:\\test.zip"//打包后文件名字缓缓
System.out.println(zipFileName)
zip(zipFileName, new File(inputFileName))
}
private void zip(String zipFileName, File inputFile) throws Exception {
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName))
zip(out, inputFile, "")
System.out.println("zip done")
out.close()
}
private void zip(ZipOutputStream out, File f, String base) throws Exception {
if (f.isDirectory()) {
File[] fl = f.listFiles()
out.putNextEntry(new org.apache.tools.zip.ZipEntry(base + "/"))
base = base.length() == 0 ? "" : base + "/"缓稿
for (int i = 0i <fl.lengthi++) {
zip(out, fl[i], base + fl[i].getName())
}
}else {
out.putNextEntry(new org.apache.tools.zip.ZipEntry(base))
FileInputStream in = new FileInputStream(f)
int b
System.out.println(base)
while ( (b = in.read()) != -1) {
out.write(b)
}
in.close()
}
}
public static void main(String [] temp){
CompressBook book = new CompressBook()
try {
book.zip("c:\\c")//你要压缩的文件夹
}catch (Exception ex) {
ex.printStackTrace()
}
}
}
public class TestZip {
public static String SERPEROT = /
public static int BUFFER =
public static void main(String args[]){
zip( e:/hello/ e:/hello zip )
}
public static void zip(String srcFile String descFile){
ZipOutputStream zos = null
FileOutputStream fos = null
File file = null
try {
fos = new FileOutputStream(descFile)
zos = new ZipOutputStream(fos)
file = new File(srcFile)
String folder = srcFile substring(srcFile lastIndexOf( / ) + srcFile length())
zip(zos file folder)
} catch (FileNotFoundException e) {
e printStackTrace()
}finally{
笑雀铅try{
if(zos != null){zos close()}
if(fos != null){fos close()}
岁雹}catch(Exception e){
e printStackTrace()
}
}
}
private static void zip(ZipOutputStream descFile File srcFile String srcfolder){
FileInputStream fis = null
System out println(srcFile isDirectory())
try{
if(srcFile isDirectory()){
File[] files = srcFile listFiles()
descFile putNextEntry(new ZipEntry(srcfolder + / ))//是压缩包里面的路径
碰好 srcfolder = srcfolder length() == ? : srcfolder + /
System out println(srcfolder)
for(int i= i<files lengthi++){
zip(descFile files[i] srcfolder + files[i] getName())
}
}else{
descFile putNextEntry(new ZipEntry(srcfolder))
fis = new FileInputStream(srcFile)
byte[] bytes = new byte[ ]
int n =
while((n = fis read(bytes)) != ){
descFile write(bytes n)
}
}
}catch(Exception e){
e printStackTrace()
}finally{
try{
if(fis != null){fis close()}
}catch(Exception e){
e printStackTrace()
}
}
}
lishixinzhi/Article/program/Java/hx/201311/25760
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)