首页 > 代码库 > java实现文件目录压缩
java实现文件目录压缩
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class MyZip {
private static void zip(File zipFile,File sourceFile) throws Exception{
ZipOutputStream out=new ZipOutputStream(new FileOutputStream(zipFile));
process(out,sourceFile,"");
out.close();
}
/**
* 递归形式写入zip文件
* @param zipOutputStreamzip输出流
* @param sourceFile源文件
* @param base 父级路径
* @throws Exception
*/
private static void process(ZipOutputStream zipOutputStream,File sourceFile,String base) throws Exception{
if(sourceFile.isDirectory()){
File[] fl=sourceFile.listFiles();
zipOutputStream.putNextEntry(new ZipEntry(base+sourceFile.getName()+"/"));
base=base+sourceFile.getName()+"/";
for(int i=0;i<fl.length;++i){
process(zipOutputStream,fl[i],base);
}
}else{
zipOutputStream.putNextEntry(new ZipEntry(base+sourceFile.getName()));
FileInputStream in=new FileInputStream(sourceFile);
zipOutputStream.setComment("www.mldnjava.cn");
int b;
while((b=in.read())!=-1){
zipOutputStream.write(b);
}
in.close();
}
}
public static void main(String[] args) throws Exception {
MyZip.zip(new File("e:" +File.separator + "HelloJava.zip"),new File( "e:" + File.separator + "HelloJava.java"));
}
}
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class MyZip {
private static void zip(File zipFile,File sourceFile) throws Exception{
ZipOutputStream out=new ZipOutputStream(new FileOutputStream(zipFile));
process(out,sourceFile,"");
out.close();
}
/**
* 递归形式写入zip文件
* @param zipOutputStreamzip输出流
* @param sourceFile源文件
* @param base 父级路径
* @throws Exception
*/
private static void process(ZipOutputStream zipOutputStream,File sourceFile,String base) throws Exception{
if(sourceFile.isDirectory()){
File[] fl=sourceFile.listFiles();
zipOutputStream.putNextEntry(new ZipEntry(base+sourceFile.getName()+"/"));
base=base+sourceFile.getName()+"/";
for(int i=0;i<fl.length;++i){
process(zipOutputStream,fl[i],base);
}
}else{
zipOutputStream.putNextEntry(new ZipEntry(base+sourceFile.getName()));
FileInputStream in=new FileInputStream(sourceFile);
zipOutputStream.setComment("www.mldnjava.cn");
int b;
while((b=in.read())!=-1){
zipOutputStream.write(b);
}
in.close();
}
}
public static void main(String[] args) throws Exception {
MyZip.zip(new File("e:" +File.separator + "HelloJava.zip"),new File( "e:" + File.separator + "HelloJava.java"));
}
}
java实现文件目录压缩
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。