Creating, Reading, and Writing: Everything about Java Directory

We often require directories aka folders in our computers, laptops, etc. This helps us in organizing our files and data so that it is easy to access and maintain. The Java directory is nothing different from the usual directories or folders. Of course, in java, we will not do it manually but will use this simple language to do our work.

On the internet, there is a lot of scattered stuff that talks about either creating, or reading or writing the directories in Java. That’s why I decided to make a full in-depth guide that covers the java directories all-inclusive.

Introduction to the Java Directories

Java directory is a way to organize the files into specific directories. There are basically four main classes involved in the directories operations in Java. These classes will be used in the examples of this tutorial. Wherever necessary, we will explain the classes and methods.

The four classes are: File, Files, Path, and Paths.

Let’s first start with section of creating the Java Directory:

Creating the Directories in Java

There are several ways to create directories in Java. Each approach of creating a Java directory has minor differences but the end result is almost same – ‘The java directory is created’.

In Java , there exists four ways of creating directories. It can be done using the methods :

  • mkdir()
  • mkdirs()
  • createDirectory()
  • createDirectories()

We will explore each method and will see where you should use which one of the method to create the Directory in Java.

File class offers two methods for creating the Java Directory – mkdir() and mkdirs(). Each has its own importance. Similarly, Files class as well provides two methods for creating of directory – createDirectory() and createDirectories().

Let’s understand each method with example:

File.mkdir()

mkdir() method is present in the File class of Java. It is used to create directory in Java. It does not have any parameters and it returns boolean value.

We invoke this method with abstract pathname and it creates the directory with the provided name. It returns true if it creates the directory and false if it it does not create the directory.

Syntax to use this method is like:

boolean flag = new File("E://parent_dir/child_dir").mkdir()

But wait, there is a catch in this method. This method will only create the directory if the parent directory does exist otherwise it won’t create the directory.

For example, as we have passed path – ‘E://parent_dir/child_dir‘ in the above code snippet then in this case it will create the directory only if the parent_dir directory/folder exists in the E:/ directory. Otherwise, it will return false.

Let’s explore the example of creating a Java Directory using mkdir() method:

package com.main;

import java.io.File;

public class MkdirExample {

	public static void main(String[] args) {

		try {
			boolean fileCreated = new File("E://path/directory_mkdir").mkdir();
			System.out.println(fileCreated);
			
		} catch (Exception e) {
			System.out.println(e);
		}

	}
}

With the above example using mkdir(), the directory – directory_mkdir will only be created if the directory path already exists. Otherwise, it would return false and will not create the directory.

File.mkdirs()

mkdirs() method is also present in the File class. This method also have null parameters and it returns true if it creates the directory and false for vice versa.

We invoke this method with abstract pathname and it creates the directory with the provided name.

But What is the difference between mkdir() and mkdirs():

The difference is mkdirs() will not stop if the parent directory does not exist. Rather, it creates the parent directory as well if it doesn’t exist.

Syntax is similar:

boolean flag = new File("E://parent_dir/child_dir").mkdirs()

Let’s explore the example of creating a Java Directory using mkdirs() method:

package com.main;

import java.io.File;

public class MkdirsExample {

	public static void main(String[] args) {

		try {

			boolean fileCreated2 = new File("E://path/directory_mkdirs").mkdirs();
			System.out.println(fileCreated2);
			
		} catch (Exception e) {
			System.out.println(e);
		}

	}
}

With the above example using mkdirs(), the directory – directory_mkdirs will be created whether the directory path exists or not. In case, parent directory does not exist then it will also create the parent directory along with child / main.

Files.createDirectory()

The createDirectory() method is present in the Files class and it is used for creating the directories in Java. However, it works a little different from the mkdir() and mkdirs() methods.

The createDirectory() method has null arguments and it returns the Path for directory.

Syntax is like:

Path path = Files.createDirectory(Paths.get("E://path/dir_createdirectory"));

In case the parent directory(path) does not exist then it won’t create the directory(dir_createdirectory) and it will raise a java.nio.file.NoSuchFileException Java exception. In case the directory(dir_createdirectory), which you are trying to create, is already exist then also it throws an exception – java.nio.file.FileAlreadyExistsException.

Let’s take a look at the full example:

package com.main;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class CreateDirectoryExample {

	public static void main(String[] args) {
		try {
			 Path path = Files.createDirectory(Paths.get("E://path/dir_createdirectory"));
			 System.out.println(path);
		}
		catch(Exception e)
		{
			System.out.println(e);
		}

	}

}

Pro tip:

Always enclose the code in try-catch block when invoking createDirectory() or/and createDirectories().

Files.createDirectories()

createDirectories() is the method present in the Files class. It is used to create java directory.

the difference between createDirectory() and createDirectories() is that the latter does not raises exception even if parent directory does not exist and even if the directory is already exist.

In case parent dir does not exist, it will create one. It also has none arguments and it returns Path of the directory.

Example:

package com.main;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class CreateDirectoriesExample {

	public static void main(String[] args) {
		try {
			 Path path = Files.createDirectories(Paths.get("E://path/dir_createdirectories"));
			 System.out.println(path);
		}
		catch(Exception e)
		{
			System.out.println(e);
		}

	}

}

mkdir() vs mkdirs() vs createDirectory() vs createDirectories()

Keymkdir()mkdirs()createDirectory()createDirectories()
Where this method belongs? FileFileFilesFiles
Creates Directory?YesYesYesYes
What if directory already exists?It returns false.returns false. It raises the exception – java.nio.file.FileAlreadyExistsExceptionRaises the exception – java.nio.file.FileAlreadyExistsException
What if parent directory does not exist?returns false.creates the parent directory along with the main directory.Throws the exception – java.nio.file.NoSuchFileExceptioncreates the parent directory along with the main directory.
Returns?booleanbooleanPathPath
Raises Exception?NoNoYesYes
Atomicity?NoneNoneExistence checking and creation of the directory is Atomic.Similar as createDirectory()

Reading/Listing the Java Directories

We have created the directories using Java, now it’s time to learn the skills of listing the directories, display the directories, display the files list in a directory, and read the directories etc.

There are various method to list the directories in Java. The class File has five different methods to list the directories in Java. Let’s explore each:

File.list()

The method list() of File class returns the String array. It has none arguments.

The list() method returns the name of all files and directories for the folder(excluding the sub-directories or/and files in subdirectories. The ordering of the list is not certain.

If the path aka directory, which is passed to list, doesn’t exist then the list() method will return null.

Let’s explore the example to list the directories using list() method:

package com.main.read;

import java.io.File;

public class ListExample {

	public static void main(String[] args) {
		try {
			File directory = new File("E://path");

			String[] fileNames = directory.list();

			for (String name : fileNames) {
				System.out.println(name);
			}

		} catch (Exception e) {
			System.out.println(e);
		}
	}

}

Please note:

list() method only returns the name of the files and not the objects. This method should be used when you just want the names of the files and directories.

File.listFiles()

The method listFiles() of File returns the array of File objects. Unlike, the list() method, this does not only contains the name but it returns array having File objects. Thus, we can perform fruther operations on the returned directories.

Similar to the list() method, it also returns null in case the path aka directory, which is passed to list, doesn’t exist. The listFiles() method only returns the directories and files (it does not return the subdirectories or files from subdirectories).

Let’s take a look at the example:

package com.main.read;

import java.io.File;

public class ListFilesExample {

	public static void main(String[] args) {
		try {
			File directory = new File("E://path");

			File[] files = directory.listFiles();

			for (File file : files) {
				System.out.println(file);
			}

		} catch (Exception e) {
			System.out.println(e);
		}
	}

}

File.list(FilenameFilter filter)

list() is a overloaded method in the File class. One has none and another has one arguments. list() method is very similar to its overloaded method list(FilenameFilter filter).

The simple difference is that the latter accepts FilenameFilter as the argument. So we can filter out the files and directories based on some condition. This is the added advantage in this method.

Similar to the list() method, it only returns the name of directories and not the objects.

if the provided filter is null, it will return the original list of directory names.

In this example, we will filter out the directories which are .txt. Let’s take a look:

package com.main.read;

import java.io.File;
import java.io.FilenameFilter;
import java.nio.file.DirectoryStream.Filter;

public class ListWithFilterExample {

	public static void main(String[] args) {
		try {
			File directory = new File("E://path");

			FilenameFilter txtFileFilter = new FilenameFilter() {
				@Override
				public boolean accept(File dir, String name) {
					if (name.endsWith(".txt")) {
						return true;
					} else {
						return false;
					}
				}
			};

			String[] files = directory.list(txtFileFilter);

			for (String file : files) {
				System.out.println(file);
			}

		} catch (Exception e) {
			System.out.println(e);
		}
	}

}

Note: this doesn’t list the subdirectories and subfiles.

File.listFiles(FilenameFilter filter)

listFiles(FilenameFilter filter) returns the filtered File objects for the invoking Path.

This is very similar to its overloaded method listFiles(). The only difference is that this one accepts the FilenameFilter.

If the provided filter is null then it will return the original list of File objects.

Let’s take a look at the example:

package com.main.read;

import java.io.File;
import java.io.FilenameFilter;

public class ListFilesWithNameFilterExample {

	public static void main(String[] args) {
		try {
			File directory = new File("E://path");

			FilenameFilter txtFileFilter = new FilenameFilter() {
				@Override
				public boolean accept(File dir, String name) {
					if (name.startsWith("a")) {
						return true;
					} else {
						return false;
					}
				}
			};

			File[] files = directory.listFiles(txtFileFilter);

			for (File file : files) {
				System.out.println(file);
			}

		} catch (Exception e) {
			System.out.println(e);
		}
	}

}

File.listFiles(FileFilter filter)

This method has only one difference from the above method that this accepts FileFilter. Other than that, everything is same in the methods listFiles(FilenameFilter) and listFiles(FileFilter).

This method is used when we want to extract the list of directories using some filter on the File objects.

In the below example, we are filtering the File objects which are the Directory type aka folders:

package com.main.read;

import java.io.File;
import java.io.FileFilter;

public class ListFilesWithFileFilterExample {

	public static void main(String[] args) {
		try {
			File directory = new File("E://path");

			FileFilter txtFileFilter = new FileFilter() {

				@Override
				public boolean accept(File dir) {
					if(dir.isDirectory()) {
						return true;
					}else {
						return false;
					}
					
				}
				
			};

			File[] files = directory.listFiles(txtFileFilter);

			for (File file : files) {
				System.out.println(file);
			}

		} catch (Exception e) {
			System.out.println(e);
		}
	}

}

How to list the directories and subdirectories in Java?

All the above methods can only list the directories and files from the provided Path. But this list does not include subdirectories and files from subdirectories as well.

It is possible to do so. In this example, we are using recursion to list the subdirectories, directories, and files:

package com.main.read;

import java.io.File;

public class ListSubDirectory {

	private static void listFiles(String path) {
		
		File folder = new File(path);

		File[] files = folder.listFiles();

		for (File file : files) {
			if (file.isFile()) {
				System.out.println(file.getName());
			} else if (file.isDirectory()) {
				System.out.println(file.getName());
				listFiles(file.getAbsolutePath());
			}
		}
	}

	public static void main(String[] args) {

		listFiles("E://path");

	}

}

Write to a File in specific Java Directory

There are various approaches to write to a file in Java. In this section, we will cover how you can write a File from a specific directory in Java.

Let’s take a look at the example:

package com.main.write;

import java.io.File;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;

public class WriteFileExample {

	public static void getFileObject(File dir) throws IOException {
		FilenameFilter txtFileFilter = new FilenameFilter() {
			@Override
			public boolean accept(File dir, String name) {
				if (name.equals("a.txt")) {
					return true;
				} else {
					return false;
				}
			}
		};

		File[] files = dir.listFiles(txtFileFilter);

		for (File file : files) {
			write(file);
		}
	}

	public static void write(File file) throws IOException {
		FileWriter writer = new FileWriter(file);
		writer.write("Hello World!");
		writer.close();
	}

	public static void main(String[] args) {

		try {
			File file = new File("E://path");
			getFileObject(file);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

The above example is pretty much easy to understand. First, we have extracted the directories from a Path then we filtered the directories using a File name and then we wrote on that specific file.

Conclusion

Thanks a lot for Reading! We have covered the Java Directory with various examples in this tutorial. You can also refer the official documentation by Oracle here.

The complete code examples can be downloaded from Github.

If you happen to like this article, let me know in the comments section or social media.

Newsletter Updates

Enter your name and email address below to subscribe to our newsletter

Leave a Reply