如何使用 Java 中的檔案實用程式方法建立目錄?
自 Java 7 以來,引入了 File.02s 類,其中包含操作檔案、目錄或其他型別檔案(靜態)方法。
Files 類的createDirectory() 方法接受所需目錄的路徑並建立一個新目錄。
示例
以下 Java 示例從使用者那裡讀取要建立目錄的路徑和名稱,並建立它。
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 Test {
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 name of the desired a directory: ");
pathStr = pathStr+sc.next();
//Creating a path object
Path path = Paths.get(pathStr);
//Creating a directory
Files.createDirectory(path);
System.out.println("Directory created successfully");
}
}輸出
Enter the path to create a directory: D: Enter the name of the desired a directory: sample_directory Directory created successfully
如果您驗證,您可以看到建立的目錄如下 -

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 Test {
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 name of the desired a directory: ");
pathStr = pathStr+sc.next();
//Creating a path object
Path path = Paths.get(pathStr);
//Creating a directory
Files.createDirectories(path);
System.out.println("Directories created successfully");
}
}輸出
Enter the path to create a directory: D: Enter the name of the desired a directory: sample/test1/test2/test3/final_folder Directory created successfully
如果您驗證,您可以看到建立的目錄如下 -

廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP