Topics Index

Input/Output: Exploring > File >
Siva Nookala - 06 Apr 2016
To create directories we use two methods mkdir() and mkdirs(). The mkdir() method creates a directory, returning true on success and false on failure. Failure can occur for various reasons, such as the path specified in the File object already exists, or the directory cannot be created because the entire path does not exist ye. To create a directory for which no path exists, use the mkdirs() method. It creates both a directory and all the parents of the directory.

Making Directories

class CreatingDirectoryDemo
    public static void main(String arg[])
        File filePath = new File("C://House/Kitchen/Refrigerator/Vegetables"); // LILNE
                                                                                // A
        filePath.mkdirs(); // LINE B
            System.out.println("Directory exists");
            System.out.println("No directory found");
        File newfile = new File(filePath, "Tomato.txt"); // LINE C
        if(newfile.createNewFile()) // LINE D
            System.out.println("File Created");
            System.out.println("File not created");    

Directory exists
File Created


In the above program at LINE A we are set the path for filePath.
At LINE B we created the directories by using the method <b>mkdirs()</b>
At LINE C we created a new File object and set the path. At LINE D we created the text file by name Tomato

  • Create directory inside House as House -> BedRoom.
  • Create a text file myBed.txt inside BedRoom

Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App