如何使用Java创建目录层次结构?
java.io 包中的名为**File**的类表示系统中的文件或目录(路径名)。此类提供各种方法来对文件/目录执行各种操作。
此类的**mkdir()**方法创建一个由当前对象表示的路径的目录。
创建目录层次结构
在 Java 中创建目录层次结构主要有两种方法:
- 使用 mkdirs() 方法
- 使用 createDirectories() 方法
让我们逐一看看这些解决方案。
使用 mkdirs() 方法
要创建新的目录层次结构,可以使用同一个类的**mkdirs()**方法。此方法创建由当前对象表示的路径的目录,包括不存在的父目录。
示例
import java.io.File;
import java.util.Scanner;
public class CreateDirectory {
public static void main(String args[]) {
System.out.println("Enter the path to create a directory: ");
Scanner sc = new Scanner(System.in);
String path = sc.next();
System.out.println("Enter the name of the desired a directory: ");
path = path+sc.next();
//Creating a File object
File file = new File(path);
//Creating the directory
boolean bool = file.mkdirs();
if(bool) {
System.out.println("Directory created successfully");
}else {
System.out.println("Sorry couldn't create specified directory");
}
}
}
输出
Enter the path to create a directory: D:\test\myDirectories\ Enter the name of the desired a directory: sample_directory Directory created successfully
如果验证,您可以看到创建的目录如下:

使用 createDirectories() 方法
从 Java 7 开始引入了 Files 类,它包含(静态)方法,这些方法可对文件、目录或其他类型的文件进行操作。
**createDirectories()**方法创建给定的目录,包括不存在的父目录。
示例
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;
public class Demo {
public static void main(String args[]) throws IOException {
System.out.println("Enter the path to create a directory: ");
Scanner sc = new Scanner(System.in);
String pathStr = sc.next();
System.out.println("Enter the required directory hierarchy: ");
pathStr = pathStr+sc.next();
//Creating a path object
Path path = Paths.get(pathStr);
//Creating a directory
Files.createDirectories(path);
System.out.println("Directory hierarchy created successfully");
}
}
输出
Enter the path to create a directory: D: Enter the required directory hierarchy: sample1/sample2/sapmle3/final_directory Directory hierarchy created successfully
如果验证,您可以看到创建的目录层次结构如下:

广告
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP