How do I create a directories recursively?

The code below use File.mkdirs() method to create a collection of directories recursively. It will create a directory with all its necessary parent directories.

package org.kodejava.example.io;

import java.io.File;

public class CreateDirs {
    public static void main(String[] args) {
        // Define a deep directory structures and create all the 
        // directories at once.
        String directories = "/Users/kodejava/a/b/c/d/e/f/g/h/i";
        File file = new File(directories);

        // The mkdirs will create folder including any necessary 
        // but nonexistence parent directories. This method returns 
        // true if and only if the directory was created along with 
        // all necessary parent directories.
        boolean result = file.mkdirs();
        System.out.println("Status = " + result);
    }
}

How do I get operating system temporary directory / folder?

To get the location of temporary directory we can use the System.getProperty(String) method and pass a property key "java.io.tmpdir" as the argument to the method.

package org.kodejava.example.lang;

public class TempDirExample {
    public static void main(String[] args) {
        // This is the property name for accessing OS temporary directory
        // or folder.
        String property = "java.io.tmpdir";

        // Get the temporary directory and print it.
        String tempDir = System.getProperty(property);
        System.out.println("OS temporary directory is " + tempDir);
    }
}

How do I rename a file or directory?

package org.kodejava.example.io;

import java.io.File;
import java.io.IOException;

public class FileRenameExample {
    public static void main(String[] args) throws IOException {
        // Creates a new file called OldHouses.csv
        File oldFile = new File("OldHouses.csv");
        oldFile.createNewFile();

        // Creates the target file.
        File newFile = new File("NewHouses.csv");

        // The renameTo() method renames file or directory to a
        // new name by passing the new destination file.
        oldFile.renameTo(newFile);
    }
}

How do I create a new directory in Java?

We create a directory by calling mkdir() method of the File object. This method returns true if and only if the directory was successfully created. If false was returned, no directory is created. This could be caused, for example that the directory was already exists.

package org.kodejava.example.io;

import java.io.File;

public class CreateDirectoryExample {
    public static void main(String[] args) {
        File file = new File("tempdir");

        if (file.mkdir()) {
            System.out.println("Directory = " + file.getAbsolutePath() + ".");
        } else {
            System.out.println("No directory was created.");
        }
    }
}

Here is the result of the program:

Directory = /Users/kodejava/Projects/kodejava/tempdir.