zl程序教程

您现在的位置是:首页 >  后端

当前栏目

java按照目录结构压缩文件夹以及文件夹内内容详解编程语言

JAVA编程语言 详解 结构 目录 以及 内容 文件夹
2023-06-13 09:20:23 时间
12 private String zipFileName; // 目的地Zip文件 13 private String sourceFileName; //源文件(带压缩的文件或文件夹) 15 public ZipCompress(String zipFileName,String sourceFileName) 16 { 17 this.zipFileName=zipFileName; 18 this.sourceFileName=sourceFileName; 19 } 21 public void zip() throws Exception 22 { 23 //File zipFile = new File(zipFileName); 24 System.out.println("压缩中..."); 26 //创建zip输出流 27 ZipOutputStream out = new ZipOutputStream( new FileOutputStream(zipFileName)); 29 //创建缓冲输出流 30 BufferedOutputStream bos = new BufferedOutputStream(out); 32 File sourceFile = new File(sourceFileName); 34 //调用函数 35 compress(out,bos,sourceFile,sourceFile.getName()); 37 bos.close(); 38 out.close(); 39 System.out.println("压缩完成"); 41 } 43 public void compress(ZipOutputStream out,BufferedOutputStream bos,File sourceFile,String base) throws Exception 44 { 45 //如果路径为目录(文件夹) 46 if(sourceFile.isDirectory()) 47 { 49 //取出文件夹中的文件(或子文件夹) 50 File[] flist = sourceFile.listFiles(); 52 if(flist.length==0)//如果文件夹为空,则只需在目的地zip文件中写入一个目录进入点 53 { 54 System.out.println(base+"/"); 55 out.putNextEntry( new ZipEntry(base+"/") ); 56 } 57 else//如果文件夹不为空,则递归调用compress,文件夹中的每一个文件(或文件夹)进行压缩 58 { 59 for(int i=0;i flist.length;i++) 60 { 61 compress(out,bos,flist[i],base+"/"+flist[i].getName()); 62 } 63 } 64 } 65 else//如果不是目录(文件夹),即为文件,则先写入目录进入点,之后将文件写入zip文件中 66 { 67 out.putNextEntry( new ZipEntry(base) ); 68 FileInputStream fos = new FileInputStream(sourceFile); 69 BufferedInputStream bis = new BufferedInputStream(fos); 71 int tag; 72 System.out.println(base); 73 //将源文件写入到zip文件中 74 while((tag=bis.read())!=-1) 75 { 76 out.write(tag); 77 } 78 bis.close(); 79 fos.close(); 81 } 82 } 83 }

 

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/7953.html

cjava