如何在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()**方法將不會建立它。
廣告