您的位置:首页 > 编程语言 > Java开发

java 删除指定文件目录

2018-01-07 00:31 393 查看
今天没事 回头看看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)");
}
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 删除 文件夹