java创建文件夹删除文件夹
时间: 2024-10-08 13:19:49 浏览: 42
在Java中,你可以使用`java.io.File`类来操作文件和目录。以下是创建文件夹和删除文件夹的基本步骤:
**创建文件夹(Directory)**:
```java
import java.io.File;
public class Main {
public static void main(String[] args) {
File directory = new File("path/to/directory"); // 文件夹路径
try {
if (!directory.exists()) { // 如果文件夹不存在则创建
boolean created = directory.mkdir(); // mkdir()方法用于创建目录
if (created) {
System.out.println("Directory created successfully.");
} else {
System.out.println("Failed to create the directory.");
}
} else {
System.out.println("Directory already exists.");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
**删除文件夹**:
```java
import java.io.File;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
File directory = new File("path/to/directory");
boolean isDirectory = directory.isDirectory(); // 检查是否为目录
if (isDirectory) {
if (directory.delete()) { // 删除目录
System.out.println("Directory deleted successfully.");
} else {
System.out.println("Failed to delete the directory.");
}
} else {
System.out.println("Path is not a directory.");
}
}
}
```
这里需要注意的是,删除文件夹时如果该文件夹非空,则不会成功删除。此外,上述代码应在异常处理中适当捕获可能出现的`IOException`。
阅读全文
相关推荐



















