Creating a directory in Java
- Eclipse: Oxygen
- Java: 1.8
Creating a directory in Java
In this tutorial, we will deal with the creation of the file directory, which has the same procedure as the creation of the file. Therefore the same concepts are shown as the absolute and relative location.
The following constructor takes a file object to create the directory. First, we create a file object using File() method as follows:
File directory = new File(“StudyEasy.txt”);
As in the previous example of creating a file in Java, we can create a directory in Java, the only difference is that we need to use the mkdir() method to create a directory in Java.
1 2 3 4 5 6 7 8 9 10 11 12 |
import java.io.File; public class Main { public static void main(String[] args) { { File directory = new File("studyeasy"); directory.mkdir(); System.out.println("directory created"); } } } |
Here is the program that demonstrates creating a subfolder inside the directory. We use mkdirs() method instead of mkdir(). With mkdirs() you can create a file inside the directory of the leaf folder in your path, the path will be interpreted as relative to the current project.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import java.io.File; public class Main { public static void main(String[] args) throws IOException { { File directory = new File("c:\\studyeasy\\author\\chaand"); directory.mkdirs(); System.out.println("directory created"); File file = new File("c:\\studyeasy\\author\\chaand\\test.txt"); file.createNewFile(); System.out.println("File created"); } } } |
Contributed by: Poonam Tomar