失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > Java生成压缩文件(zip rar 格式)

Java生成压缩文件(zip rar 格式)

时间:2020-04-10 05:54:48

相关推荐

Java生成压缩文件(zip rar 格式)

在开发过程成遇到要把多个文件打包压缩的需求

maven配置

<dependency><groupId>org.apache.ant</groupId><artifactId>ant</artifactId><version>1.10.5</version></dependency>

代码示例:

/*** @param path 要压缩的文件路径* @param format 生成的格式(zip、rar)d*/public static void generateFile(String path, String format) throws Exception {File file = new File(path);// 压缩文件的路径不存在if (!file.exists()) {throw new Exception("路径 " + path + " 不存在文件,无法进行压缩...");}// 用于存放压缩文件的文件夹String generateFile = file.getParent() + File.separator +"CompressFile";File compress = new File(generateFile);// 如果文件夹不存在,进行创建if( !compress.exists() ){compress.mkdirs();}// 目的压缩文件String generateFileName = compress.getAbsolutePath() + File.separator + "AAA" + file.getName() + "." + format;// 输入流 表示从一个源读取数据// 输出流 表示向一个目标写入数据// 输出流FileOutputStream outputStream = new FileOutputStream(generateFileName);// 压缩输出流ZipOutputStream zipOutputStream = new ZipOutputStream(new BufferedOutputStream(outputStream));generateFile(zipOutputStream,file,"");System.out.println("源文件位置:" + file.getAbsolutePath() + ",目的压缩文件生成位置:" + generateFileName);// 关闭 输出流zipOutputStream.close();}/*** @param out 输出流* @param file 目标文件* @param dir 文件夹* @throws Exception*/private static void generateFile(ZipOutputStream out, File file, String dir) throws Exception {// 当前的是文件夹,则进行一步处理if (file.isDirectory()) {//得到文件列表信息File[] files = file.listFiles();//将文件夹添加到下一级打包目录out.putNextEntry(new ZipEntry(dir + "/"));dir = dir.length() == 0 ? "" : dir + "/";//循环将文件夹中的文件打包for (int i = 0; i < files.length; i++) {generateFile(out, files[i], dir + files[i].getName());}} else {// 当前是文件// 输入流FileInputStream inputStream = new FileInputStream(file);// 标记要打包的条目out.putNextEntry(new ZipEntry(dir));// 进行写操作int len = 0;byte[] bytes = new byte[1024];while ((len = inputStream.read(bytes)) > 0) {out.write(bytes, 0, len);}// 关闭输入流inputStream.close();}}// 测试public static void main(String[] args) {String path = "";String format = "rar";try {generateFile(path, format);} catch (Exception e) {e.printStackTrace();System.out.println(e.getMessage());}}

如果觉得《Java生成压缩文件(zip rar 格式)》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。