Wednesday, April 12, 2023

How to Create File and Directory in Java with Example

Many beginners confused with the fact that the same class java.io.File is used to create both file and directories in Java. I agree, this is not very intuitive and junior developers probably start looking for a class called java.io.Directory, which doesn't exist. On the other hand, creating file and directories are simple in Java, as java.io.File provides methods like createNewFile() and mkdir() to create new file and directory in Java. These methods returns boolean, which is the result of that operation i.e. createNewFile() returns true if it successfully created file and mkdir() returns true if the directory is created successfully. 

There is another method called mkdirs(), which you can use if parent directory doesn't exist, it's like mkdir -p option from UNIX mkdir command. In this Java program, we will learn how to create file and directory, only if they don't exist already.

For checking, whether a file or directory exists or not, we will use java.io.File.exists() method, this method returns true, if file or directory is already there. To see complete behaviour in action, please run this program twice with same inputs. First time it will create directory and file, and second time, it will just say that they already exists.



Java Program to make File and Directory

This is the complete code of our sample Java program to create files and directories in Java. As I told same object java.io.File is used to represent both file and directory,  its important to name variable properly to distinguish between them e.g. using prefix "f" for file and "dir" for the directory, or something similar.  

In this example, we are asking user to enter path of directory to be created, and using scanner to read data from console. Scanner.nextLine() returns a String, so no need of any additional parsing.


After that, we are checking if directory already exists or not by using exists() method from java.io.File class, extremely useful to prevent accidental overwrite of old data. If directory doesn't already exists then we call mkdir() method from File class to actually create a directory, thankfully name is similar to the popular command mkdir, which is used to create directory in both Windows and Linux operating systems. 

This method returns a boolean value, which can be used to check if creation of directory is successful or not, you can either leverage this value for error handling or printing error message.

Once directory is ready, we are creating a File object by passing string path. This file object is further used to check if any file of same name already exists on same location or not. If not then only we create file, using createNewFile() of java.io.File class. 

Java Program to create File and Directory in Java
Similar to mkdir() method, this also returns a boolean to pass result of operation. It will return true if file is successfully created otherwise false, which may be due to various reasons e.g. not having sufficient permissions to create file, or there is not enough space to accommodate new files etc. After creating, you can also use Scanner to read file in Java, as shown in that article.

Code Sample

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

/**
* Simple Java program to create File and Directory in Java, without using
* any third-party library.
* @author http://java67.blogspot.com
*
*/
public class FileDemo {

    public static void main(String args[]) throws IOException {

        Scanner reader = new Scanner(System.in);
        boolean success = false;

        System.out.println("Enter path of directory to create");
        String dir = reader.nextLine();

        // Creating new directory in Java, if it doesn't exists
        File directory = new File(dir);
        if (directory.exists()) {
            System.out.println("Directory already exists ...");

        } else {
            System.out.println("Directory not exists, creating now");

            success = directory.mkdir();
            if (success) {
                System.out.printf("Successfully created new directory : %s%n", dir);
            } else {
                System.out.printf("Failed to create new directory: %s%n", dir);
            }
        }

        // Creating new file in Java, only if not exists
        System.out.println("Enter file name to be created ");
        String filename = reader.nextLine();

        File f = new File(filename);
        if (f.exists()) {
            System.out.println("File already exists");

        } else {
            System.out.println("No such file exists, creating now");
            success = f.createNewFile();
            if (success) {
                System.out.printf("Successfully created new file: %s%n", f);
            } else {
                System.out.printf("Failed to create new file: %s%n", f);
            }
        }

        // close Scanner to prevent resource leak
        reader.close();

    }
}

Output :

First run :
Enter path of directory to create
C:\dhoom3
Directory not exists, creating now
Successfully created new directory : C:\dhoom3
Enter file name to be created
Abhishek.txt
No such file exists, creating now
Successfully created new file: Abhishek.txt

Second run :
Enter path of directory to create
C:\dhoom3
Directory already exists ...
Enter file name to be created
Abhishek.txt
File already exists

Don't forget to close Scanner once done, a good practice to prevent resource leaks in Java. Alternatively, you can also use try-with-resources statements from Java 7, which facilitate automatic resource clean-up for you. That not only take care of releasing resources once you are done with that, but also removes coding headache and finally block from above code, making it more concise and readable.

That's all about how to create or make files and directories in Java.



4 comments:

  1. There are a few errors in your code.

    1. The code
    File directory = new File(dir);
    if (directory.exists()) { ... }
    doesn't check directory is directory. So here:
    File directory = new File(dir);
    if (directory.exists() && directory.isDirectory()) { ... }

    2. The same for file:
    String filename = reader.nextLine();
    File f = new File(filename);
    if (f.exists() && f.isFile()) { ... }

    Enjoy Java! -)

    ReplyDelete
  2. I guess the code above have another error.
    When creating the newFile, it is not created in the recently created directory. Instead is located in the ProjectDirectory.
    Any help?

    ReplyDelete
    Replies
    1. Just modify the arguments in this line

      File f = new File(directory,filename);
      success = f.createNewFile();

      It will solve your problem.

      From Saumendra......

      Delete

Feel free to comment, ask questions if you have any doubt.