JAVA - Zero to Hero / File Handling

Working with Directories

πŸ“ Working with Directories in Java

Java allows you to create, delete, check, and list directories (folders) using the File class from the java.io package. Think of a directory as just another kind of file object β€” but one that holds other files or folders.


1️⃣ Step 1: Import the File Class

import java.io.File;

2️⃣ Step 2: Create a File Object Representing a Directory

File folder = new File("MyFolder");

☝️ This does NOT create a folder on your computer. It just creates a File object in memory that represents a folder named "MyFolder" in your current working directory.


πŸ”¨ Creating Directories

πŸ†• mkdir() – Create a Single Folder

boolean created = folder.mkdir();
  • Creates only one directory.

  • Returns true if the folder was created successfully.

  • Returns false if:

    • The folder already exists

    • Parent folders don't exist

    • Some error occurred

βœ… Example:

File folder = new File("MyFolder");
if (folder.mkdir()) {
    System.out.println("Folder created successfully.");
} else {
    System.out.println("Failed to create folder.");
}

πŸ†• mkdirs() – Create Multiple Nested Folders

File nestedFolder = new File("Parent/Child/Java");
nestedFolder.mkdirs();
  • Creates all missing parent folders in the path.

  • Useful when creating deeply nested folder structures.

βœ… Example:

File folder = new File("Java/Files/Examples");
if (folder.mkdirs()) {
    System.out.println("Nested folders created.");
} else {
    System.out.println("Failed to create folders.");
}

πŸ” Checking Directory Properties

πŸ“ isDirectory() – Check if it's a folder

if (folder.isDirectory()) {
    System.out.println("It is a directory.");
}

πŸ“„ isFile() – Check if it's a file

if (folder.isFile()) {
    System.out.println("It is a file.");

πŸ“œ Listing Folder Contents

πŸ—ƒοΈ list() – Returns file/folder names inside a directory

String[] items = folder.list();
for (String item : items) {
    System.out.println(item);
}
  • Only works if the folder exists and is a directory.

  • Returns null if it’s not a directory or doesn’t exist.


πŸ—‘οΈ Deleting a Directory

❌ delete() – Deletes an Empty Folder

if (folder.delete()) {
    System.out.println("Folder deleted.");
} else {
    System.out.println("Failed to delete folder.");
}

⚠️ Only works for empty folders. You cannot delete a folder that contains files/subfolders without first deleting its contents manually.


βœ… Full Working Example:

import java.io.File;

public class DirectoryExample {
    public static void main(String[] args) {
        File folder = new File("MyFolder");

        // Creating the folder
        if (!folder.exists()) {
            if (folder.mkdir()) {
                System.out.println("Folder created.");
            } else {
                System.out.println("Failed to create folder.");
            }
        }

        // Check if it's a directory
        if (folder.isDirectory()) {
            System.out.println("Confirmed: It's a folder.");

            // Listing contents
            String[] files = folder.list();
            if (files.length == 0) {
                System.out.println("The folder is empty.");
            } else {
                System.out.println("Folder contains:");
                for (String name : files) {
                    System.out.println(name);
                }
            }
        }

        // Delete folder if empty
        if (folder.delete()) {
            System.out.println("Folder deleted.");
        } else {
            System.out.println("Cannot delete folder (maybe not empty).");
        }
    }
}

πŸ“‚ SCENARIO 2: "MyFolder" already exists and is not empty

Let’s say it contains a file like notes.txt.

Confirmed: It's a folder.
Folder contains:
notes.txt
Cannot delete folder (maybe not empty)

βœ… Explanation:

  • The folder already exists, so mkdir() is skipped.

  • It lists the contents using list().

  • Since the folder is not empty, folder.delete() fails.


πŸ“‚ SCENARIO 3: "MyFolder" exists and is empty

Confirmed: It's a folder.
The folder is empty.
Folder deleted.βœ… Explanation:
  • Since it’s already created and empty, it gets deleted directly.


🧠 Summary Table:

Method

Description

mkdir()

Creates a single folder

mkdirs()

Creates nested folders

isDirectory()

Checks if the path is a directory

isFile()

Checks if the path is a file

list()

Lists file/folder names inside a directory

delete()

Deletes an empty folder