多個文件壓縮
/** * 原生代碼 * 將一個圖片與一個視頻文件壓縮到 test.zip 中 */ public static void main(String[] args) throws IOException { //壓縮文件名稱與位置 OutputStream outputStream = new FileOutputStream("f://test.zip"); //獲取壓縮文件輸出流 ZipOutputStream out = new ZipOutputStream(outputStream); //被壓縮的文件 FileInputStream fis = new FileInputStream("F://video.mp4"); //video.mp4在壓縮包zip 中的音樂名稱 out.putNextEntry(new ZipEntry("視頻.mp4")); int len; byte[] buffer = new byte[1024]; // 讀入需要下載的文件的內容,打包到zip文件 while ((len = fis.read(buffer)) > 0) { //寫入壓縮文件輸出流中(壓縮文件zip中) out.write(buffer, 0, len); } fis.close(); //第二個被壓縮文件 FileInputStream fis1 = new FileInputStream("F://picture.jpg"); //picture.jpg在壓縮包中的名稱 圖片.jpg out.putNextEntry(new ZipEntry("圖片.jpg")); int len1; byte[] buffer1 = new byte[1024]; // 讀入需要下載的文件的內容,打包到zip文件 while ((len1 = fis1.read(buffer1)) > 0) { out.write(buffer1, 0, len1); } //關閉流 out.closeEntry(); fis1.close(); out.close(); }
zip文件解壓
/** * zip壓縮文 解壓 */ public static void main(String[] args) throws IOException { //讀取壓縮文件 ZipInputStream in = new ZipInputStream(new FileInputStream("f://test.zip")); //zip文件實體類 ZipEntry entry; //遍歷壓縮文件內部 文件數量 while((entry = in.getNextEntry()) != null){ if(!entry.isDirectory()){ //文件輸出流 FileOutputStream out = new FileOutputStream( "f://java_zip/"+entry.getName()); BufferedOutputStream bos = new BufferedOutputStream(out); int len; byte[] buf = new byte[1024]; while ((len = in.read(buf)) != -1) { bos.write(buf, 0, len); } // 關流順序,先打開的后關閉 bos.close(); out.close(); } } }