Create/Delete Directory ,File

In the section of Java Tutorial you will learn how to create directory using java program. This program also explains the process of creating all non-existent ancestor directories automatically. We will use the class File class to crate the directory.

Class File
The File class an abstract representation of file and directory pathnames. File class is used to interact with the files system.

Here is the code for creating directory and all non-existing ancestor directories:

class CreateDirectory
public static void main(String args[])
String strDirectoy ="test";
String strManyDirectories="dir1/dir2/dir3";

// Create one directory
boolean success = (new File(strDirectoy)).mkdir();
if (success) {
System.out.println("Directory: " + strDirectoy + " created");

// Create multiple directories
success = (new File(strManyDirectories)).mkdirs();
if (success) {
System.out.println("Directories: " + strManyDirectories + " created");

}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());

This example illustrates how to delete the specified file or directory after checking weather the file exists or not. This topic is related to the I/O (input/output) of package.

In this example we are using File class of package. The File class is an abstract representation of file and directory pathnames.


This program deletes the specified file if that exists. We will be declaring a function called deletefile which deletes the specified directory or file.

deletefile(String file)

The function deletefile(String file) takes file name as parameter. The function creates a new File instance for the file name passed as parameter

File f1 = new File(file);

and delete the file using delete function f1.delete(); which return the Boolean value (true/false). It returns true if and only if the file or directory is successfully deleted; false otherwise.


Deletes the file or directory denoted by this abstract pathname. If this pathname denotes a directory, then the directory must be empty in order to be deleted.

true if and only if the file or directory is successfully deleted; false otherwise

Code of the Program :


public class DeleteFile{
private static void deletefile(String file){
File f1 = new File(file);
boolean success = f1.delete();
if (!success){
System.out.println("Deletion failed.");
System.out.println("File deleted.");
public static void main(String[] args){
case 0: System.out.println("File has not mentioned.");
case 1: deletefile(args[0]);
default : System.out.println("Multiple files are not allow.");


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s