Java的文件压缩-Zip格式

1/** 2 * 文件压缩 3 */ 4public class ZipFile_Compress { 5 public static void main(String[] args) throws IOException { 6 File file = new File("E:\\aaa\\web01"); 7 8 String savePath = "E:\\aaa" + File.separator + file.getName() + ".zip"; 9 File saveFile = new File(savePath); 10 if (!saveFile.getParentFile().exists()) { 11 saveFile.getParentFile().mkdirs(); 12 } 13 14 ZipOutputStream outputStream = new ZipOutputStream(new FileOutputStream(savePath, true)); 15 16 toMakeZipFilePre(file, saveFile.getParentFile().getPath(), outputStream); 17 18 outputStream.close(); 19 } 20 21 /** 22 * 文件压缩前的准备处理 23 * @param file 24 * @param savePath 25 * @param outputStream 26 * @throws IOException 27 */ 28 public static void toMakeZipFilePre(File file, String savePath, ZipOutputStream outputStream) throws IOException { 29 if (file.isDirectory()) { 30 File[] files = file.listFiles(); 31 if (files != null) { 32 for (File f : files) { 33 toMakeZipFilePre(f, savePath, outputStream); 34 } 35 } 36 } else { 37 /** 38 * 截取后面要用的文件条目 39 */ 40 String realSavePath = file.getAbsolutePath().substring(savePath.length() + 1).replaceAll("\\\\", "/"); 41 toMakeZipFile(file, realSavePath, outputStream); 42 System.out.println(realSavePath); 43 } 44 } 45 46 public static void toMakeZipFile(File file, String savePath, ZipOutputStream outputStream) throws IOException { 47 /** 48 * 将相对路径封装成条目 49 */ 50 ZipEntry zipEntry = new ZipEntry(savePath); 51 /** 52 * 在输出流中编写一条新的条目 53 */ 54 outputStream.putNextEntry(zipEntry); 55 56 InputStream inputStream = new BufferedInputStream(new FileInputStream(file)); 57 58 int len = 0; 59 byte[] bytes = new byte[1024]; 60 while ((len = inputStream.read(bytes)) != -1) { 61 outputStream.write(bytes, 0, len); 62 } 63 outputStream.flush(); 64 inputStream.close(); 65 } 66 67}
点赞
收藏

评论区

加载中...

相关推荐

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

Java中zip的压缩和解压缩

在Java中可以使用ZipOutputStream和ZipInputStream来实现zip的压缩和解压缩操作,另外使用FileSystem也可以用来实现zip的解压缩,下面将介绍这几种方式,直接上代码。zip压缩待压缩文件目录结构:!(https://static.oschina.net/uploads/img/202102/2

Linux下创建加密的压缩文件

Linux下创建加密的压缩文件方法一:1.使用ZIP命令创建一个加密的ZIP文件:2.解压缩加密文件时,会提示要求输入密码:方法二:1.使用7z创建一个zip文件:2.解压缩加密文件:3.使用限制方法三:1.Tocre

JAR WAR EAR的使用和区别

1.JARWAREAR的使用和区别最近项目中接触到了JarWarEAR,在文件结构上,三者并没有什么不同,它们都采用zip或jar档案文件压缩格式,当时它们的使用有所区别:Jar(JavaApplicationArchive)文件包含Java类的普通库,资源辅助文件

linux常见压缩格式及deb安装包用法

ZIP格式评价:可能是目前使用的最多的文档压缩格式,跨平台。压缩率不高。压缩一个目录:\ziprarchive\_name.zipdirectory\_to\_compress解压缩:\unziparchive\_name.zipTAR格式评价:消耗cpu及时间少,仅仅是一个打包工具,并不负责压缩。

Linux基础学习笔记——压缩和解压(tar、zip)

压缩和解压缩Linux默认支持的压缩格式:gz、bz2、zip压缩目的:节省磁盘空间扩展:1.压缩文件尽量使用gz,因为占用空间较少,效率高;2.bz2压缩后的文件占用空间最小;3.zip压缩的文件占用空