在操作.zip的压缩包时,可以用到高级流ZipInputStream和ZipOutputStream。.zip文件中的每个文件夹和文件都是一个ZipEntry对象。解压和压缩的本质就是操作每个ZipEntry对象,只能操作后缀为.zip的文件
1 解压.zip文件
ZipInputStream,解压。是将硬盘上的.zip的文件读取到内存中,根据流向的分类,属于输入流。遍历并读取其中的ZipEntry内容写到指定的文件中。
/*** @Author lyf* @Date 2023/10/14 - 20:48* @Description 解压缩流 [zip格式的文件]* 压缩包中的每一个文件(文件夹)就是一个ZipEntry对象* 解压的过程就是把每一个ZipEntry 拷贝到另外的目的路径中* (硬盘上)压缩包——内存 ZipInputStream 解压**/
public class ZipInputStreamStudy {public static void main(String[] args) throws IOException {//需要解压的压缩文件File originFile=new File( "C:\\Users\\XXXX\\Desktop\\a.zip");//解压后的目标路径File descFile=new File("C:\\Users\\XXXX\\Desktop\\aa\\dd\\cc");if(!descFile.exists()){descFile.mkdirs();}zip(originFile,descFile);}/*** 解压缩动作* @param originFile zip文件* @param descFile 目标路径*/private static void zip(File originFile, File descFile) throws IOException{//创建zip字节输入流关联压缩文件ZipInputStream zipInputStream=new ZipInputStream(new FileInputStream(originFile));//遍历读取每一个zipEntryZipEntry zipEntry;while ((zipEntry=zipInputStream.getNextEntry())!=null){//如果是文件夹,在目的地创建文件夹if(zipEntry.isDirectory()){File mkfile=new File(descFile,zipEntry.toString());mkfile.mkdir();}else{//如果是文件,copy到目的地File toFile=new File(descFile,zipEntry.toString());FileOutputStream fileOutputStream=new FileOutputStream(toFile);int len;while ((len=zipInputStream.read())!=-1){fileOutputStream.write(len);}fileOutputStream.close();zipInputStream.closeEntry();//关闭压缩包中的entry}}zipInputStream.close();}
}
2 压缩文件
ZipOutputStream,压缩。是将文件夹中的内容压缩成为一个.zip文件写出到硬盘上,根据流向的分类,属于输出流
/*** @Author lyf* @Date 2023/10/14 - 21:19* @Description 压缩输出流* 每个文件、文件夹都是一个zipEntry对象,压缩的本质就是将zipEntry对象放到目标文件夹中。* (硬盘)本地文件——(内存)压缩——(硬盘)压缩后的zip包 ZipOutStream**/
public class ZipOutputStreamStudy {public static void main(String[] args) throws IOException {//源文件夹File originFile =new File("C:\\Users\\xxxx\\Desktop\\sql");//目标文件夹File desDic = new File("C:\\Users\\xxxx\\Desktop\\aa");if(!desDic.exists()){//不存在时,创建路径,避免创建流失败desDic.mkdirs();}//获得当前文件夹下的所有子项【文件或文件夹】if(originFile.isFile()){throw new RuntimeException("需要选择文件夹!");}//目标zipZipOutputStream zos = new ZipOutputStream(new FileOutputStream(new File(desDic,originFile.getName()+".zip")));//递归处理zipDic(originFile,originFile.getName(),zos);//释放资源zos.close();}/*** 压缩整个文件夹* @param originFile 需要压缩的目标文件夹* @param name 压缩包的内部路径* @param zos 操作zip的流* @throws IOException*/private static void zipDic(File originFile,String name,ZipOutputStream zos)throws IOException {File[] files = originFile.listFiles();for (File file : files) {if(file.isDirectory()){zipDic(file,name+"\\"+file.getName(),zos);}else{FileInputStream fis = new FileInputStream(file);BufferedInputStream bi=new BufferedInputStream(fis); //将输入流转为带有缓存的输入流ZipEntry zipEntry = new ZipEntry(name+"\\"+file.getName());zos.putNextEntry(zipEntry);byte[]bytes=new byte[1024*1024*5];//一次读5M大小字节的数据int len;while ((len = bi.read(bytes)) != -1) {zos.write(bytes,0,len);}//关闭缓存流bi.close();//当前的zipEntryzos.closeEntry();}}}
}