java 把文件和目录文件夹压缩成 zip 格式的

2015-08-12 13:49:55来源:作者:人点击

package text;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.util.zip.ZipEntry;

import java.util.zip.ZipOutputStream;

//=====================目录压缩=========================

public class ZipFile {

/*

* inputFileName 输入一个文件夹 zipFileName 输出一个压缩文件夹

*/

public static void zip(String inputFileName) throws Exception {

String zipFileName = "E://test.zip"; // 打包后文件名字

//System.out.println(zipFileName);

zip(zipFileName, new File(inputFileName));

}

private static 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 static void zip(ZipOutputStream out, File f, String base) throws Exception {

if (f.isDirectory()) {

File[] fl = f.listFiles();

out.putNextEntry(new ZipEntry(base + "/"));

base = base.length() == 0 ? "" : base + "/";

for (int i = 0; i < fl.length; i++) {

zip(out, fl[i], base + fl[i].getName());

}

} else {

out.putNextEntry(new 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){      

try {          

zip("E://ftl");//你要压缩的文件夹       

}catch (Exception ex) {      

ex.printStackTrace();   

}  

}

}

//=====================目录压缩=========================

//=====================文件压缩=========================

/*//把文件压缩成zip

File zipFile = new File("E:/demo.zip");

//定义输入文件流

InputStream input = new FileInputStream(file);

//定义压缩输出流 

ZipOutputStream zipOut = null;

//实例化压缩输出流,并制定压缩文件的输出路径  就是E盘下,名字叫 demo.zip

zipOut = new ZipOutputStream(new FileOutputStream(zipFile));

zipOut.putNextEntry(new ZipEntry(file.getName()));

//设置注释

zipOut.setComment(" www.demo.com ");

int temp = 0;

while((temp = input.read()) != -1) {

zipOut.write(temp); 

}  

input.close();

zipOut.close();*/

//==============================================

获取【下载地址】

/

微信扫一扫

第七城市微信公众平台