使用 Java 將多個文件壓縮成一個壓縮文件java
1、內容數組
①使用 Java 將多個文件打包壓縮成一個壓縮文件;spa
②主要使用 java.io 下的類code
2、源代碼:ZipMultiFile.java對象
1 package cn.com.zfc.day018; 2 3 import java.io.File; 4 import java.io.FileInputStream; 5 import java.io.FileOutputStream; 6 import java.io.IOException; 7 import java.util.zip.ZipEntry; 8 import java.util.zip.ZipOutputStream; 9 10 /** 11 * @describe 壓縮多個文件 12 * @author zfc 13 * @date 2018年1月11日 下午8:34:00 14 */ 15 public class ZipMultiFile { 16 17 public static void main(String[] args) { 18 File[] srcFiles = { new File("E:\\母親.mp4"), new File("E:\\飛機.pdf"), new File("E:\\家裏密碼.txt") }; 19 File zipFile = new File("E:\\ZipFile.zip"); 20 // 調用壓縮方法 21 zipFiles(srcFiles, zipFile); 22 } 23 24 public static void zipFiles(File[] srcFiles, File zipFile) { 25 // 判斷壓縮後的文件存在不,不存在則建立 26 if (!zipFile.exists()) { 27 try { 28 zipFile.createNewFile(); 29 } catch (IOException e) { 30 e.printStackTrace(); 31 } 32 } 33 // 建立 FileOutputStream 對象 34 FileOutputStream fileOutputStream = null; 35 // 建立 ZipOutputStream 36 ZipOutputStream zipOutputStream = null; 37 // 建立 FileInputStream 對象 38 FileInputStream fileInputStream = null; 39 40 try { 41 // 實例化 FileOutputStream 對象 42 fileOutputStream = new FileOutputStream(zipFile); 43 // 實例化 ZipOutputStream 對象 44 zipOutputStream = new ZipOutputStream(fileOutputStream); 45 // 建立 ZipEntry 對象 46 ZipEntry zipEntry = null; 47 // 遍歷源文件數組 48 for (int i = 0; i < srcFiles.length; i++) { 49 // 將源文件數組中的當前文件讀入 FileInputStream 流中 50 fileInputStream = new FileInputStream(srcFiles[i]); 51 // 實例化 ZipEntry 對象,源文件數組中的當前文件 52 zipEntry = new ZipEntry(srcFiles[i].getName()); 53 zipOutputStream.putNextEntry(zipEntry); 54 // 該變量記錄每次真正讀的字節個數 55 int len; 56 // 定義每次讀取的字節數組 57 byte[] buffer = new byte[1024]; 58 while ((len = fileInputStream.read(buffer)) > 0) { 59 zipOutputStream.write(buffer, 0, len); 60 } 61 } 62 zipOutputStream.closeEntry(); 63 zipOutputStream.close(); 64 fileInputStream.close(); 65 fileOutputStream.close(); 66 } catch (IOException e) { 67 e.printStackTrace(); 68 } 69 70 } 71 }
3、運行結果blog