java.io.File mkdir()

Description

On this document we will be showing a java example on how to use the mkdir() method of File Class. This method creates the directory named by this abstract pathname.

Throws:

  • SecurityException – If a security manager exists and its SecurityManager.checkWrite(java.lang.String) method does not permit the named directory to be created.

Method Syntax

public boolean mkdir()

Method Argument

Data Type Parameter Description
N/A N/A N/A

Method Returns

This method returns boolean, true if and only if the directory was created; false otherwise.

Compatibility

Requires Java 1.0 and up

Java File mkdir() Example

Below is a java code demonstrates the use of mkdir() method of File class. The example presented might be simple however it shows the behaviour of the mkdir() method of File class. Basically we called this method and we put a check on the returned value to check if the file specified has been created successfully or not.

The example provided below shows that on the first run, the file has been created successfully while on the second run it failed. That is because the file is already created on the first run, thus succeeding run will definitely fail as describe on the earlier part of this document.

package com.javatutorialhq.java.examples;

import java.io.File;

/*
 * This example source code demonstrates the use of  
 * mkdir() method of File class.
 * 
 */

public class FileMkdirExample {

	public static void main(String[] args) {
		
		// initialize File object
		File file = new File("C:javatutorialhqtest_folder");		
		// check if the pathname already exists
		// if not create it
		if(!file.exists()){
			// create the folder
			boolean result = file.mkdir();
			if(result){
				System.out.println("Successfully created "+file.getAbsolutePath());
			}
			else{
				System.out.println("Failed creating "+file.getAbsolutePath());
			}
		}else{
			System.out.println("Pathname already exists");
		}
	}
}

Sample Output

Below is the sample output when you run the above example.

java lang File mkdir() example output