Saturday, 13 February 2016

Create a new directory using Java

In today's example we'll create a new directory using Java. Check out the following code below :

import java.io.*;

public class Create_Directory {

public static void main(String[] args) {
File dir = new File("//Users//ironcladzone//Downloads//TestDir");
boolean DirectoryCreated = dir.mkdir();
if (DirectoryCreated)
System.out.println("Created a new directory");
else
System.out.println("Directory not created");
}


}

Note that we have used the function mkdir() as expected. It returns the value "true" if the directory is created or "false" if not created. We use the variable 'DirectoryCreated' to store this boolean value, based on which it prints a message.

Try executing this program twice. The first time when you execute the program, a directory gets created and you get the output like :

Created a new directory

The second time when you execute the code, a directory does not get created since it already exists. So you'll get the output like :

Directory not created

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...
eXTReMe Tracker