How to Create Directory in Java


In this example, we will learn how to create a directory in Java.

Source Code

package com.beginner.examples;
 
import java.io.File;
import java.io.IOException;
 
public class CreateDir {
	public static void main(String[] args) {
		String path ="E:tmp"; //File directory created
		File f = new File(path); 
		if(!f.exists()){
			f.mkdirs(); 
		}
		String fileName = "Text.txt"; 
		File file = new File(path,fileName);
		if(!file.exists()){ 
			try { 
				file.createNewFile();
				System.out.println("The file " + fileName + " is successfully created!");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

Output:

The file Text.txt is successfully created!

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments