1. 程式人生 > >java 刪除指定檔案目錄

java 刪除指定檔案目錄

今天沒事 回頭看看IO流的問題呢,順便整理下刪除檔案的步驟。畢竟曾經也是讓我頭疼的問題。

本來想將刪除目錄以及子目錄都放在一個方法處理的(在一個方法中只能刪除子目錄,執行完這個方法才會執行刪除最外層目錄的程式碼),但是沒能處理的了,因為時間緊張也就沒往下想(其實這樣也挺好,簡單、易懂)。希望各位知道正解後 可以告知,相同進步麼

首先,理清資料夾和檔案的刪除方式,資料夾要用到回撥函式(很重要喲),檔案直接刪除即可。其次就是對異常的處理 很是重要

不多說,上碼:

package com.tpad.deldir;

import java.io.File;
import java.io.IOException;
import javax.swing.JOptionPane;

public class DelDir {

public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
// 建立一個File物件,封裝目錄
try {
String dirFullPath = "d:\\floder";
DelDir dd = new DelDir();
dd.delDir(dirFullPath);
dd.delSelf(dirFullPath);
JOptionPane.showMessageDialog(null, "ok");
} catch (IOException e) {
// TODO: handle exception
JOptionPane.showMessageDialog(null, e.getMessage());
}
}

// 刪除子檔案目錄
public void delDir(String dirFullPath) throws IOException {
// TODO Auto-generated method stub
File dirFile = new File(dirFullPath);
// 獲取該目錄下所有檔案或資料夾的File陣列
File[] fileArr = dirFile.listFiles();
// 檢驗陣列是否為空
if (fileArr == null) { // 這裡要想清楚,如果子資料夾為空,這裡會不會執行下面的異常。 若你有這個疑問,認真想下陣列以及listFiles()
throw new IOException(dirFile.getPath() + " (The system cannot find the specified source file)");
}
// 遍歷File陣列,得到每一個File物件
for (File file : fileArr) {
if (file.isDirectory()) {
delDir(file.toString());
if (file.delete() == false) {
throw new IOException(file.getPath() + " (Folder deletion failed)");
}
} else {
if (file.delete() == false) {
throw new IOException(file.getPath() + " (File deletion failed)");
}
}
}
}

// 刪除父檔案目錄(最外層)
private void delSelf(String dirFullPath) throws IOException {
// TODO Auto-generated method stub
File dirFile = new File(dirFullPath);
if(dirFile.exists()) {
if(dirFile.delete() == false) {
throw new IOException(dirFile.getPath() + " (The system cannot find the specified source file)");
}
}
}
}