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

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();*/
//==============================================

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。