如何在 Java 中使用 File 对象创建新目录?
名为 File 的 java.io 包中的类表示系统中的文件或目录(路径名)。此类提供多种方法来对文件/目录执行各种操作。
创建新目录
此类的 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() 方法将不会创建它。
创建目录层次结构
要创建新目录的层次结构,可以使用同一类的 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 couldnt 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
如果验证,您可以观察到创建的目录如下 -

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