Curriculum
Course: Learn Java Programming
Login

Curriculum

Learn Java Programming

Video lesson

Creating a File and Directory in Java

In this lesson, you will learn

  • What is File
  • Creating a File
  • Creating a Directory
  • Creating a File Inside a Directory

 

What is a File?

1. The File class is part of the java.io package and provides functionalities for creating, reading, and modifying files and directory pathnames.

2. It offers methods to perform operations such as creating, deleting, and querying file attributes, as well as checking permissions.

 

The File class does not provide methods for file content manipulation; instead, it mainly handles file metadata and filesystem operations.

 

Create a File Using the File Class

To create a new file in Java using the File class, you would typically follow these steps:

1. Create an instance of the File class representing the filename and directory path where you want the file to be located. The following are the constructors to create files

File(String directoryPath)
File(String directoryPath, String filename)

Here, directoryPath is the path name of the file; filename is the name of the file

 

2. Use the createNewFile method to physically create the file on the filesystem.

Operations with the File class can throw an IOException, so it’s necessary to handle this exception either with a try-catch block or by throwing it further.

 

Example 1: Creating a File

The following program creates a file as we have not mentioned any path so myfile.txt will be created in the project directory.

 

package creatingfile;

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

public class CreateFile {

	public static void main(String[] args) throws IOException {
		File file = new File("myfile.txt");
		if (file.createNewFile()) {
			System.out.println("File Created");
		} else {
			System.out.println("File Not Created");
		}	
	}
}

Output

File Created

 

The following program creates the file inside a folder. For a Windows machine, the part starts with (/ or \), and the path will be interpreted as relative to the current project.

 

package creatingfile;

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

public class CreateFile {

	public static void main(String[] args) throws IOException {
		File file = new File("src/creatingfile/myfile.txt");
		if (file.createNewFile()) {
			System.out.println("File Created");
		} else {
			System.out.println("File Not Created");
		}	
	}
}

Output

File Created

 

The following code snippet creates a file in the absolute path.

File file = new File("G:\jcodebook\author\myfile.txt");

 

What is a Directory?

  • A directory is a file system object that can contain multiple files and other directories.

Creating Directories and Sub-directories Using the File Class

To create directories and sub-directories using the File class, you can use the mkdir() and mkdirs() methods.

package directories;

import java.io.File;

public class DirectoryExample {
    public static void main(String[] args) {
        // Create a single directory
        File dir = new File("jcodebook");
        if (dir.mkdir()) {
            System.out.println("Directory created: " + dir.getName());
        } else {
            System.out.println("Failed to create directory, "
            		+ "it may already exist");
        }

        // Create multiple directories (sub-directories)
        File subdirs = new File("jcodebook/subdir1/subdir2");
        if (subdirs.mkdirs()) {
            System.out.println("Sub-directories created: " + subdirs.getPath());
        } else {
            System.out.println("Failed to create sub-directories, "
            		+ "they may already exist");
        }
    }
}

Output

Directory created: jcodebook
Sub-directories created: jcodebooksubdir1subdir2

 

Difference between mkdir() and mkdirs()

The mkdir() Method

The mkdir() method creates the new directory name and only succeeds if the parent directory already exists. It does not create any parent directories.

//Create a directory in an existing parent directory
File dir = new File("existingParentDir/newDir");
if (dir.mkdir()) {
    System.out.println("Directory created: " + dir.getName());
} else {
    System.out.println("Failed to create directory 
        or it already exists.");
}

In this example, newDir will only be created if existingParentDir already exists. If existingParentDir does not exist, mkdir() will fail.

 

The mkdirs()

The mkdirs() method attempts to create the directory named by this abstract pathname, including any necessary but nonexistent parent directories.

//Create a directory and necessary non-existent parents
File dirs = new File("newParentDir/subDir");
if (dirs.mkdirs()) {
	System.out.println("Directories created successfully "
			+ "along the path: " +dirs.getPath());
} else {
	System.out.println("Failed to create directories "
			+ "or they already exist.");
}

This example will create both newParentDir and subDir if they do not exist.

This is useful when you want to ensure the entire directory path is set up as expected without manually creating each level.

 

Summary

  • mkdir() is suitable when you are sure that the parent directory already exists and you just need to create a new directory within it.
  • mkdirs() should be used when you might need to create multiple levels of directories, and you are not sure if the parent directories exist; it ensures that the whole path is created if necessary.

 

Creating a File Inside a Directory

 

Example: Create a File Inside a Directory

package directories;

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

public class DirectoryExample2 {

	public static void main(String[] args) throws IOException {
		File dir = new File("jcodebook/author/amit");
        dir.mkdirs();
        System.out.println("directory created");
        File file = new File("jcodebook/author/amit/myfile.txt");
        file.createNewFile();
        System.out.println("file created");
	}
}

Output

directory created
file created

 


End of the lesson….enjoy learning

 

 

Student Ratings and Reviews

 

 

 

There are no reviews yet. Be the first one to write one.

 

 

Submit a Review