java删除文件夹
时间:2022-05-04
本文章向大家介绍java删除文件夹,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
想删除本地一个项目目录,结果windows说路径太长,不能删除。于是试了试java删除。一切ok。以后一定要抓紧时间学python。
/**
* Created by rmiao on 4/21/2016.
*/
public class TestDel {
public static void main(String[] args) throws IOException {
String dest = "D:\perforce\workspace2\EPC";
File file = new File(dest);
forceDelete(file);
}
private static void forceDelete(File file) throws IOException {
if (file.isDirectory()){
deleteDirectory(file);
}else{
boolean filePresent = file.exists();
if(!file.delete()){
if(!filePresent){
throw new FileNotFoundException("File does note exist:"+file);
}
String message = "Unable to delete file:"+file;
throw new IOException(message);
}else{
System.out.println("-"+file.getAbsolutePath());
}
}
}
public static void deleteDirectory(File directory) throws IOException{
if (directory.exists()){
cleanDirectory(directory);
}
if(!directory.delete()){
String message = "Unable to delete directory "+directory+".";
throw new IOException(message);
}
}
/**
* Cleans a directory without deleting it.
*
* @param directory directory to clean
* @throws IOException in case cleaning is unsuccessful
*/
public static void cleanDirectory(File directory) throws IOException {
if (!directory.exists()) {
String message = directory + " does not exist";
throw new IllegalArgumentException(message);
}
if (!directory.isDirectory()) {
String message = directory + " is not a directory";
throw new IllegalArgumentException(message);
}
File[] files = directory.listFiles();
if (files == null) { // null if security restricted
throw new IOException("Failed to list contents of " + directory);
}
IOException exception = null;
for (File file : files) {
try {
forceDelete(file);
} catch (IOException ioe) {
exception = ioe;
}
}
if (null != exception) {
throw exception;
}
}
}
- java教程
- Java快速入门
- Java 开发环境配置
- Java基本语法
- Java 对象和类
- Java 基本数据类型
- Java 变量类型
- Java 修饰符
- Java 运算符
- Java 循环结构
- Java 分支结构
- Java Number类
- Java Character类
- Java String类
- Java StringBuffer和StringBuilder类
- Java 数组
- Java 日期时间
- Java 正则表达式
- Java 方法
- Java 流(Stream)、文件(File)和IO
- Java 异常处理
- Java 继承
- Java 重写(Override)与重载(Overload)
- Java 多态
- Java 抽象类
- Java 封装
- Java 接口
- Java 包(package)
- Java 数据结构
- Java 集合框架
- Java 泛型
- Java 序列化
- Java 网络编程
- Java 发送邮件
- Java 多线程编程
- Java Applet基础
- Java 文档注释
- Python 基础(九):函数
- Python 基础(十二):文件基本操作
- Python 基础(十三):os 模块
- Python 基础(十四):错误和异常
- Python 基础(十五):枚举
- 一个老程序员的30年生涯回顾
- 经典 90 坦克大战 Python 版实现(支持单双人模式)
- Python 基础(十六):迭代器与生成器
- MySQL information_schema详解 COLUMNS
- MySQL information_schema详解 COLUMN_PRIVILEGES
- 一分钟学Python|Python的字典
- MySQL information_schema详解 ENGINES
- 一日一技:不用轮询,基于事件监控文件变动
- Python 基础(十七):装饰器
- XtraBackup工具详解 Part 10 使用innobackupex对数据库进行部分备份(指定表或数据库)