Java Top

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE

1. Overview

In this quick tutorial, we're going to look at how to create a file in a specific directory.

We'll see the difference between absolute and relative file paths, and we'll use paths that work on several major operating systems.

2. Absolute and Relative File Paths

2.1. Absolute Paths

Let's start with creating a file in a directory by referring to the entire path, also known as an absolute path. To demonstrate, we'll use the absolute path to the user temp directory, and add our directory and file into it.

We're using Files.touch(), which is part of Google Guava, as an easy way to create an empty file:

File tempDirectory = new File(System.getProperty("java.io.tmpdir"));
File fileWithAbsolutePath = new File(tempDirectory.getAbsolutePath() + "/myDirectory/testFile.txt");

assertFalse(fileWithAbsolutePath.exists());

Files.touch(fileWithAbsolutePath);

assertTrue(fileWithAbsolutePath.exists());

2.2. Relative Paths

We can also create a file in a directory that is relative to another directory. For instance, let's create a directory and file based on the user temp directory:

File tempDirectory = new File(System.getProperty("java.io.tmpdir"));
File fileWithRelativePath = new File(tempDirectory, "myDirectory/newFile.txt");

assertFalse(fileWithRelativePath.exists());

Files.touch(fileWithRelativePath);

assertTrue(fileWithRelativePath.exists());

In the above example, our new directory and file are added to the path of the user temp directory.

3. Using a Platform Independent File Separator

To construct file paths, we need to use separators like / or \. However, the appropriate separator to use depends upon your operating system. Luckily, there's an easier way. We can use Java's File.separator instead of separator characters. As a result, Java picks the appropriate separator for us.

Let's look at an example of creating a file with this method:

File tempDirectory = new File(System.getProperty("java.io.tmpdir"));
File newFile = new File(tempDirectory.getAbsolutePath() + File.separator + "newFile.txt");

assertFalse(newFile.exists());

Files.touch(newFile);

assertTrue(newFile.exists());

Using File.separator, Java knows how to construct paths based on the underlying filesystem.

4. Conclusion

In this article, we explored the differences between absolute and relative paths and how to create file paths that work on several major operating systems.

As always, the example code is available over on GitHub.

Java bottom

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE
Comments are closed on this article!