- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to create Directories using the File utility methods in Java?
Since Java 7 the File.02s class was introduced this contains (static) methods that operate on files, directories, or other types of files.
The createDirectory() method of the Files class accepts the path of the required directory and creates a new directory.
Example
Following Java example reads the path and name of the directory to be created, from the user, and creates it.
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"); } }
Output
Enter the path to create a directory: D: Enter the name of the desired a directory: sample_directory Directory created successfully
If you verify, you can observe see the created directory as −
The createDirectories() method creates the given directory including the non-existing parent directory.
Example
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"); } }
Output
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
If you verify, you can observe see the created directory as −
Advertisements