JAVA 壓縮文件 -- 單個 或 多個 | 文件夾 或 文件

廢話不多說,直接上代碼:

/** 壓縮一個文件或文件夾
 * @param sourceFile 你要壓縮的文件夾(整個完整路徑)
 * @param zipFilePath 壓縮後的文件(整個完整路徑)
 * @throws Exception
 */
public static Boolean zip(String sourceFile, String zipFilePath) {
	//若目標文件已經存在,先刪除
	File target = new File(zipFilePath);
	if (target.exists())
		target.delete();
	
	ZipOutputStream out = null;
	try {
		out = new ZipOutputStream(new FileOutputStream(zipFilePath));
		File srcfile = new File(sourceFile);
		zip(srcfile,out, "");
	}
	catch (Exception e) {
		e.printStackTrace();
	} finally {
		try {
			if (out != null)
				out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	return true;
}

/** 壓縮多個文件或文件夾
 * @param sourceFileList 要壓縮的文件路徑數組(整個完整路徑)
 * @param zipFilePath 壓縮後的文件(整個完整路徑)
 * @throws Exception
 */
public static Boolean compress(LinkedList<String> sourceFileList,String zipFilePath){
	//若目標文件已經存在,先刪除
	File target = new File(zipFilePath);
	if (target.exists())
		target.delete();
	
	ZipOutputStream out = null;
	try {
		out = new ZipOutputStream(new FileOutputStream(zipFilePath));
		
		for (String sourceFile : sourceFileList) {
			File srcfile = new File(sourceFile);
			zip(srcfile,out, "");
		}
		
	}
	catch (Exception e) {
		e.printStackTrace();
	} finally {
		try {
			if (out != null)
				out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	return true;
	
}

//真正幹活的兩個方法  上面這個是包工頭,下面那個是員工         -------相當於中介
private static void zip(File srcfile,ZipOutputStream out,String base) throws Exception {
	if (srcfile.isDirectory()) {
		File[] fl = srcfile.listFiles();
		base = base.length() == 0 ? srcfile.getName()+ "/" : base + "/";
		out.putNextEntry(new ZipEntry(base));
		for (int i = 0; i < fl.length; i++) {
			zip(fl[i], out, base + fl[i].getName());
		}
	} else {
		//壓縮單個文件
		zipFile(srcfile,out,base);
	}
}

//壓縮單個文件
private static void zipFile(File srcfile, ZipOutputStream out, String basedir) {
	if (!srcfile.exists())
		return;

	//第一步就直接壓縮文件的情況  此時 basedir = 0,要加上文件名
	basedir = basedir.length() == 0 ? srcfile.getName() : basedir;
	
	byte[] buf = new byte[1024];
	FileInputStream in = null;

	try {
		int len;
		in = new FileInputStream(srcfile);
		out.putNextEntry(new ZipEntry(basedir));
		
		while ((len = in.read(buf)) > 0) {
			out.write(buf, 0, len);
			out.flush();
		}
	} catch (Exception e) {
		e.printStackTrace();
	} finally {
		try {
			if (out != null)
				out.closeEntry();          //在這裏關閉每一個小文件 的  Entry,在最上面兩個調用方法中 才 最終關閉  out
			if (in != null)
				in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

 

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