Java File mkdir() method with examples

April 28, 2020 No comments Java IO File Examples mkdir

1. Introduction

The mkdir() method creates the directory with the given name.

2. Method signature

public boolean mkdir()

Parameters:

  • method does not take any parameter

Returns

  • true - if the directory was created; false otherwise

Throws

  • SecurityException - when we do not have access to the file or directory

3. Examples

3.1. Code that creates ttt directory in /tmp folder

package com.frontbackend.java.io;

import java.io.File;

public class FrontBackend {

    public static void main(String args[]) {

        try {
            File ttt = new File("/tmp/ttt");

            System.out.println(ttt.exists()); // false - not yet

            if (ttt.mkdir()) {
                System.out.println("Directory created");
            }

            System.out.println(ttt.exists()); // true
            System.out.println(ttt.isDirectory()); // true - of course it is

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

The output:

false
Directory created
true
true

4. Conclusion

In this article, we focused on mkdir() method from Java IO, which created directory with the specified name and returns true if the directory was successfully created.

{{ message }}

{{ 'Comments are closed.' | trans }}