java壓縮文件方法

總結一下實現壓縮文件的幾個步驟:
1.創建壓縮文件的對象(一旦創建對象,就會創建對應名稱的壓縮文件)
2.創建文件入口(這裏傳入的參數是壓縮文件中的路徑,可隨意)
3.通過putNextEntry方法移動到入口上
4.進行你所需要的操作
5.關流
前三步是必須的,當然最後關流也是必須的

package com.baishiwei.myFileDemo;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class MyZipDemo {
	private void zip(String zipFileName, File inputFile) throws Exception {
		// 創建zip對象
		ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(new File(zipFileName)));
		
		// 判斷並輸出
		isDir(zipOutputStream, inputFile);
		
		// 關流
		zipOutputStream.close();
	}

	public void isDir(ZipOutputStream zipOutputStream, File file) throws IOException {
		// 判斷是否文件夾
		if (file.isDirectory()) {
			File[] listFiles = file.listFiles();
			// 判斷一下空文件夾的處理
			if (listFiles.length == 0 || listFiles == null) {
				String absolutePath = file.getAbsolutePath();
				absolutePath = absolutePath.substring(absolutePath.indexOf("\\") + 1);
				// 創建新的入口
				ZipEntry zipEntry = new ZipEntry(absolutePath + "\\");
				zipOutputStream.putNextEntry(zipEntry);
				
				// 關閉入口
				zipOutputStream.closeEntry();
			}
			for (File file2 : listFiles) {
				isDir(zipOutputStream, file2);
			}
		} else {
			// 將文件路徑的盤符去掉
			String absolutePath = file.getAbsolutePath();
			absolutePath = absolutePath.substring(absolutePath.indexOf("\\") + 1);
			
			// 設置入口
			ZipEntry zipEntry = new ZipEntry(absolutePath);
			
			// 移動到入口
			zipOutputStream.putNextEntry(zipEntry);

			// 讀取打印文件
			readFile(zipOutputStream, file);
		}
	}

	public void readFile(ZipOutputStream zipOutputStream, File file) throws IOException {
		// 輸出
		FileInputStream fileInputStream = new FileInputStream(file);
		int length = -1;
		byte[] b = new byte[1024];
		while((length = fileInputStream.read(b)) != -1) {
			zipOutputStream.write(b, 0, length);
		}
		fileInputStream.close();
	}

	public static void main(String[] temp) { // 主方法
		try {
			MyZipDemo myZipDemo = new MyZipDemo();
			myZipDemo.zip("F:\\b.zip", new File("F:\\QMDownload"));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章