Java压缩文件/文件夹
生活随笔
收集整理的這篇文章主要介紹了
Java压缩文件/文件夹
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
ZipOutputStream流、遞歸壓縮。
????????在關閉ZipOutputStream流之前,需要先調用flush()方法,強制將緩沖區所有的數據輸出,以避免解壓文件時出現壓縮文件已損壞的現象。
/*** @param source 待壓縮文件/文件夾路徑* @param destination 壓縮后壓縮文件路徑* @return*/ public static boolean toZip(String source, String destination) {try {FileOutputStream out = new FileOutputStream(destination);ZipOutputStream zipOutputStream = new ZipOutputStream(out);File sourceFile = new File(source);// 遞歸壓縮文件夾compress(sourceFile, zipOutputStream, sourceFile.getName());zipOutputStream.flush();zipOutputStream.close();} catch (IOException e) {System.out.println("failed to zip compress, exception");return false;}return true; } private static void compress(File sourceFile, ZipOutputStream zos, String name) throws IOException {byte[] buf = new byte[1024];if(sourceFile.isFile()){// 壓縮單個文件,壓縮后文件名為當前文件名zos.putNextEntry(new ZipEntry(name));// copy文件到zip輸出流中int len;FileInputStream in = new FileInputStream(sourceFile);while ((len = in.read(buf)) != -1){zos.write(buf, 0, len);}zos.closeEntry();in.close();} else {File[] listFiles = sourceFile.listFiles();if(listFiles == null || listFiles.length == 0){// 空文件夾的處理(創建一個空ZipEntry)zos.putNextEntry(new ZipEntry(name + "/"));zos.closeEntry();}else {// 遞歸壓縮文件夾下的文件for (File file : listFiles) {compress(file, zos, name + "/" + file.getName());}}} }總結
以上是生活随笔為你收集整理的Java压缩文件/文件夹的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 推荐一些实用网站
- 下一篇: Java并发57:Akka Actors