Directory Operations in Java

A directory in Java is a File object that can contain other files and directories. You can use the File class to perform operations such as creating, listing, and deleting directories.



Creating Directories

There are two methods in the File class that are useful for creating directories:

  • mkdir(): Creates a single directory and returns true on success or false on failure. Failure occurs if the directory already exists or if the parent directories are missing.
  • mkdirs(): Creates both the directory and any missing parent directories.

Example: Creating a Directory in Java

The following example creates the directory /tmp/user/java/bin.


package com.example;

import java.io.File;

public class DirectoryTest {
public static void main(String args[]) {
// Define the directory path
String dirname = "/tmp/user/java/bin";
File directory = new File(dirname);

// Create directories
directory.mkdirs();

// Check if the directory exists
File file = new File("/tmp/user/java/bin");
System.out.println(file.exists());
}
}
    

Output

true

Note: Java automatically handles path separators correctly on both UNIX and Windows platforms. You can use a forward slash (/) even on Windows.

Listing (Reading) Directories

You can use the list() method of the File class to list all the files and directories present in a directory.

Example: Listing a Directory in Java


package com.example;

import java.io.File;

public class DirectoryTest {

public static void main(String[] args) {
File file = null;
String[] paths;

try {      
    // Create a File object for the directory
    file = new File("/tmp");

    // Get an array of files and directories
    paths = file.list();

    // Print each file and directory name
    for(String path : paths) {
    System.out.println(path);
    }
} catch (Exception e) {
    e.printStackTrace();
}
}
}
    

Output

user

Deleting Directories

You can use the delete() method of the File class to delete an empty directory.

Example: Deleting a Directory in Java


package com.example;

import java.io.File;

public class DirectoryTest {

public static void main(String[] args) {
// Create a File object for the directory to be deleted
File file = new File("/tmp/user/java/bin");

if (file.exists()) {
    boolean success = file.delete();

    if (success) {
    System.out.println("The directory has been successfully deleted.");
    } else {
    System.out.println("The directory deletion failed.");
    }
} else {
    System.out.println("The directory is not present.");
}
}
}
    

Output

The directory has been successfully deleted.