1. 程式人生 > 程式設計 >java壓縮檔案與刪除檔案的示例程式碼

java壓縮檔案與刪除檔案的示例程式碼

壓縮檔案 :toZip(String srcDir,OutputStream out,boolean KeepDirStructure)

刪除檔案:deleteFolder(File folder)

/**
	 * 壓縮成ZIP 方法1
	 * 
	 * @param srcDir
	 *      壓縮資料夾路徑
	 * @param out
	 *      壓縮檔案輸出流
	 * @param KeepDirStructure
	 *      是否保留原來的目錄結構,true:保留目錄結構;
	 *      false:所有檔案跑到壓縮包根目錄下(注意:不保留目錄結構可能會出現同名檔案,會壓縮失敗)
	 * @throws RuntimeException
	 *       壓縮失敗會丟擲執行時異常
	 */
	protected void toZip(String srcDir,boolean KeepDirStructure) throws RuntimeException {
		long start = System.currentTimeMillis();
		ZipOutputStream zos = null;
		try {
			zos = new ZipOutputStream(out);
			File sourceFile = new File(srcDir);
			compress(sourceFile,zos,sourceFile.getName(),KeepDirStructure);
			long end = System.currentTimeMillis();
			System.out.println("壓縮完成,耗時:" + (end - start) + " ms");
		} catch (Exception e) {
			throw new RuntimeException("zip error from ZipUtils",e);
		} finally {
			if (zos != null) {
				try {
					zos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	/**
	 * 遞迴壓縮方法
	 * 
	 * @param sourceFile
	 *      原始檔
	 * @param zos
	 *      zip輸出流
	 * @param name
	 *      壓縮後的名稱
	 * @param KeepDirStructure
	 *      是否保留原來的目錄結構,會壓縮失敗)
	 * @throws Exception
	 */
	private static void compress(File sourceFile,ZipOutputStream zos,String name,boolean KeepDirStructure) throws Exception {
		byte[] buf = new byte[BUFFER_SIZE];
		if (sourceFile.isFile()) {
			// 向zip輸出流中新增一個zip實體,構造器中name為zip實體的檔案的名字
			zos.putNextEntry(new ZipEntry(name));
			// copy檔案到zip輸出流中
			int len;
			FileInputStream in = new FileInputStream(sourceFile);
			while ((len = in.read(buf)) != -1) {
				zos.write(buf,len);
			}
			// Complete the entry
			zos.closeEntry();
			in.close();
		} else {
			File[] listFiles = sourceFile.listFiles();
			if (listFiles == null || listFiles.length == 0) {
				// 需要保留原來的檔案結構時,需要對空資料夾進行處理
				if (KeepDirStructure) {
					// 空資料夾的處理
					zos.putNextEntry(new ZipEntry(name + "/"));
					// 沒有檔案,不需要檔案的copy
					zos.closeEntry();
				}
			} else {
				for (File file : listFiles) {
					// 判斷是否需要保留原來的檔案結構
					if (KeepDirStructure) {
						// 注意:file.getName()前面需要帶上父資料夾的名字加一斜槓,// 不然最後壓縮包中就不能保留原來的檔案結構,即:所有檔案都跑到壓縮包根目錄下了
						compress(file,name + "/" + file.getName(),KeepDirStructure);
					} else {
						compress(file,file.getName(),KeepDirStructure);
					}
				}
			}
		}
	}
/**
	 * 刪除資料夾
	 * 
	 * @param folder
	 */
	protected void deleteFolder(File folder) {
		// 待刪除檔案路徑
		String path = this.getClass().getResource("/").getPath().replace(
				"WEB-INF/classes/","postFile/");
		if (folder.isDirectory()) {
			File[] files = folder.listFiles();
			for (int i = 0; i < files.length; i++) {
				deleteFolder(files[i]);
			}
			// 非當前目錄,刪除
			if (!folder.getAbsolutePath().equalsIgnoreCase(path)) {
//				// 只刪除在7天前建立的檔案
//				if (canDeleteFile(folder)) {
//					if (folder.delete()) {
//						System.out.println("資料夾" + folder.getName() + "刪除成功!");
//					} else {
//						System.out.println("資料夾" + folder.getName()
//								+ "刪除失敗!此資料夾內的檔案可能正在被使用");
//					}
//				}
				//只要是空的資料夾就刪除不區分幾天前建立
				if (folder.delete()) {
					System.out.println("資料夾" + folder.getName() + "刪除成功!");
				} else {
					System.out.println("資料夾" + folder.getName()
							+ "刪除失敗!此資料夾內的檔案可能正在被使用");
				}
			}
		} else {
			deleteFile(folder);
		}
	}
	/**
	 * 判斷檔案是否能夠被刪除
	 */
	protected boolean canDeleteFile(File file) {
		Date fileDate = getfileDate(file);
		Date date = new Date();
		long time = (date.getTime() - fileDate.getTime()) / 1000 / 60 / 60 / 24;// 當前時間與檔案建立時間的間隔天數
		// 大於7天可刪除,小於10天不刪除
		if (time > 10) {
			return true;
		} else {
			return false;
		}
//		return true;
	}
	/**
	 * 獲取檔案最後的修改時間
	 * 
	 * @param file
	 * @return
	 */
	protected Date getfileDate(File file) {
		long modifiedTime = file.lastModified();
		Date d = new Date(modifiedTime);
		return d;
	}
	/**
	 * 刪除檔案
	 * 
	 * @param file
	 */
	protected void deleteFile(File file) {
		try {
			if (file.isFile()) {
				// 刪除符合條件的檔案
				if (canDeleteFile(file)) {
					if (file.delete()) {
						System.out.println("檔案" + file.getName() + "刪除成功!");
					} else {
						System.out.println("檔案" + file.getName()
								+ "刪除失敗!此檔案可能正在被使用");
					}
				} else {
				}
			} else {
				System.out.println("沒有可以刪除的檔案了");
			}
		} catch (Exception e) {
			System.out.println("刪除檔案失敗========");
			e.printStackTrace();
		}
	}

總結

到此這篇關於java壓縮檔案與刪除檔案的示例程式碼的文章就介紹到這了,更多相關java壓縮檔案與刪除檔案內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!