Thursday, April 23, 2020

How to Create File and Directory in Java with Example

Oracle Java Tutorial and Materials, Oracle Java Exam Prep, Oracle Java Certification

Many beginners confused with the fact that same class java.io.File is used to create both file and directory 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 exists. On the other hand, creating file and directory are simple in Java, as java.io.File provides methods like createNewFile() and mkdir() to create new file and directory in Java. These method 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.

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 file and directory 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 directory, or something similar.

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 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.

Oracle Java Tutorial and Materials, Oracle Java Exam Prep, Oracle Java Certification

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.

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://oraclejavacertified.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 leak in Java. Alternatively you can also use try-with-resource 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 file and directory in Java.

Related Posts

0 comments:

Post a Comment