Menu
Topics Index
...
`


Input/Output: Exploring java.io > 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
import java.io.*;

class CreatingDirectoryDemo
{
    public static void main(String arg[])
    {
        File filePath = new File("C://House/Kitchen/Refrigerator/Vegetables"); // LILNE
                                                                                // A
        filePath.mkdirs(); // LINE B
        
        if(filePath.exists())
            System.out.println("Directory exists");
        else
            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");
        else
            System.out.println("File not created");    
    }
}
OUTPUT

Directory exists
File Created

DESCRIPTION

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

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

0
Wrong
Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App