Selenium WebDriver Java Framework Course Limited Time Offer for $20

Selenium WebDriver Java Framework Course Limited Time Offer for $20

 

Print

Create a Directory in Java

Using java.io.File package you can create a directory. See the example below. In this example, if the directory exists, system outputs a text "Directory is already existed" or else the code will create a directory from the CreateADirectory method. 

 

package com.seleniummaster.examplefile;

import java.io.File;
import java.io.IOException;

public class CreateDirectory {

    public static void main(String[] args)
    {
        CreateADirectory("testdir1");
    }

    public static void CreateADirectory(String DirectoryName)
    {
        //project directory
        String workingDirectory = System.getProperty("user.dir");
        String  dir = workingDirectory + File.separator + DirectoryName;

        System.out.println("Final file directory : " + dir);

        //create a directory in the path

        File file = new File(dir);

        if (!file.exists()) {
            file.mkdir();
            System.out.println("Directory is created!");
        } else {
            System.out.println("Directory is already existed!");
        }

    }

    }

Run the code and see the result below.

Final file directory : C:\seleniummaster\testdir1
Directory is created!

Process finished with exit code 0

If you run the code again, you will see the text "Directory is already existed!"

Final file directory : C:\seleniummaster\testdir1
Directory is already existed!

Process finished with exit code 0