如何在Java中创建项目文件夹下的目录?
java.io包中的名为**File**的类表示系统中的文件或目录(路径名)。此类提供各种方法来对文件/目录执行各种操作。
此类的**mkdir()**方法使用当前对象表示的路径创建一个目录。
因此,要创建目录:
通过将需要创建的目录的路径作为参数(字符串)传递,实例化**File**类。
使用上面创建的文件对象调用**mkdir()**方法。
示例
以下Java示例从用户读取要创建的目录的路径和名称,并创建它。
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.mkdir();
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:\ Enter the name of the desired a directory: sample_directory Directory created successfully
如果验证,您可以看到创建的目录为:

但是,如果指定不存在的驱动器中的路径,此方法将不会创建所需的目录。
例如,如果我的(Windows)系统的**D**盘为空,并且我将要创建的目录的路径指定为:
D:\test\myDirectories\sample_directory
其中test和myDirectories文件夹不存在,**mkdir()**方法将不会创建它。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP