public class Text {
public static void main(String[] args) throws IOException, ClassNotFoundException {
//确定要压缩文件的路径
File src=new File("D:\\xx");
//确定要压缩成的文件路径
File destparent=src.getParentFile();
File dest=new File(destparent+src.getName()+".zip");
//创建压缩流连接要要压缩成的文件路径
ZipOutputStream zos=new ZipOutputStream(new FileOutputStream(dest));
toZip(src,zos,src.getName());
zos.close();
}
public static void toZip(File src,ZipOutputStream zos,String name) throws IOException {
//将要要压缩的文件其内部变成list形式
File[] files = src.listFiles();
//遍历list分为文件和非文件两种情况
for (File file : files) {
if (file.isFile()){
//创建压缩后的文件
ZipEntry ze=new ZipEntry(name+"\\"+file.getName());
//加入到压缩流中的一个文件位
zos.putNextEntry(ze);
//读取原文件的数据并写入到压缩流中
FileInputStream fis=new FileInputStream(file);
int i;
while ((i=fis.read())!=-1){
zos.write(i);
}
//关闭输入流和压缩流的一个文件位
fis.close();
zos.closeEntry();
}else {
//递归
toZip(file,zos,name+"\\"+file.getName());
}
}
}
}
压缩文件io流 java
最新推荐文章于 2024-09-27 00:45:01 发布
这篇文章详细描述了一个Java程序,使用`ZipOutputStream`实现对指定文件夹及其内容进行压缩的过程,包括读取文件、创建`ZipEntry`并将其添加到压缩流中。
摘要由CSDN通过智能技术生成