進行檔案操作時,一般的步驟如下:
讀操作:對目標檔案 new 一個輸入資料流 —> 讀取資料 —> 操作資料
寫操作:對目標檔案 new 一個輸出資料流 —> 調用write方法寫入資料
瞭解Java壓縮技術首先應該瞭解Zip檔案的結構,如下圖,一個zip檔案包含了多個ZipEntry,稱之為“條目”。
zip檔案的操作和普通檔案的操作是類似的,唯一的區別是zip檔案的資料結構不同,zip檔案是個容器,包含多個檔案。因此對zip檔案的讀寫就是對容器內檔案的讀寫。
讀操作:對目標zip檔案 new 一個zip輸入資料流 —> 對於每個條目,為該條目new一個檔案輸入資料流,讀取條目資料 —> 操作資料
寫操作:對目標zip檔案 new 一個zip輸出資料流 —> 對於每個條目,為該條目new一個檔案輸出資料流,然後寫入資料
讀操作的代碼:
@Testpublic void runZipInputStream() throws IOException {//1. 建立zip輸入資料流ZipInputStream zin = new ZipInputStream(new FileInputStream("IOTest.zip"));ZipEntry ze;//2. 逐個處理條目while ((ze = zin.getNextEntry()) != null) {//測試: 輸出條目的資訊System.out.printf("條目資訊: 名稱%1$b, 大小%2$d, 壓縮時間%3$d \n", ze.getName(), ze.getSize(), ze.getTime());//3. 操作檔案內容-輸出、處理FileInputStream fin = new FileInputStream(ze.getName());byte[] buffer = new byte[4096];int len;while ((len = fin.read(buffer)) != -1) {System.out.print(new String(buffer, 0, len));}}}
寫作業碼:
@Testpublic void runZipOutputStream() throws IOException {//1. 建立zip輸出資料流ZipOutputStream zos = new ZipOutputStream(new FileOutputStream("javaio.rar"));//2. 建立並設定條目資訊File f = new File("javaio.bmp");ZipEntry ze = new ZipEntry(f.getName());ze.setComment("Hello, Zip");ze.setSize(f.length());ze.setTime(f.lastModified());//3. 添加條目到輸出資料流zos.putNextEntry(ze);//4. 輸出FileInputStream fin = new FileInputStream(f);byte[] buffer = new byte[4096];int len;while ((len = fin.read(buffer)) != -1) {zos.write(buffer, 0, len);}fin.close();//5. 關閉流zos.close();}
上面的代碼都是對單個檔案進行操作,如果要壓縮整個目錄,就需要遍曆目錄下的所有檔案。