1. Files class

Files class

To work with files, there is a slick utility class — java.nio.file.Files. It has methods for every occasion. All the methods of this class are static and operate on Path object. There are a lot of methods, so we will consider only the most important ones:

Method Description
Path createFile(Path path)
Creates a new file whose path is path
Path createDirectory(Path path)
Creates a new directory
Path createDirectories(Path path)
Creates multiple directories
Path createTempFile(prefix, suffix)
Creates a temporary file
Path createTempDirectory(prefix)
Creates a temporary directory
void delete(Path path)
Deletes a file or directory if it is empty
Path copy(Path src, Path dest)
Copies a file
Path move(Path src, Path dest)
Moves a file
boolean isDirectory(Path path)
Checks whether the path is a directory and not a file
boolean isRegularFile(Path path)
Checks whether the path is a file and not a directory
boolean exists(Path path)
Checks whether an object exists at the given path
long size(Path path)
Returns the file size
byte[] readAllBytes(Path path)
Returns the entire contents of a file as an array of bytes
String readString(Path path)
Returns the entire contents of a file as a string
List<String> readAllLines(Path path)
Returns the entire contents of a file as a list of strings
Path write(Path path, byte[])
Writes an array of bytes to a file
Path writeString(Path path, String str)
Writes a string to a file
DirectoryStream<Path> newDirectoryStream(Path dir)
Returns a collection of files (and subdirectories) from the given directory

2. Creating files and directories

Files and directories are very easy to create. Let's convince ourselves with some examples:

Code Note
Files.createFile(Path.of("c:\\readme.txt"));
Creates a file
Files.createDirectory(Path.of("c:\\test"));
Creates a directory
Files.createDirectories(Path.of("c:\\test\\1\\2\\3"));
Creates a directory and all the necessary subdirectories if they do not exist.

3. Copying, moving and deleting

Copying, moving and deleting files is just as easy. This also applies to directories, but they must be empty.

Code Note
Path path1 = Path.of("c:\\readme.txt");
Path path2 = Path.of("c:\\readme-copy.txt");
Files.copy(path1, path2);
Copies a file
Path path1 = Path.of("c:\\readme.txt");
Path path2 = Path.of("d:\\readme-new.txt");
Files.move(path1, path2);
Moves and renames a file
Path path = Path.of("d:\\readme-new.txt");
Files.delete(path);
Deletes a file

4. Checking a file's type and existence

When you have a path provided by someone else, you want to know whether it is a file or a directory. And in general, does such a file/directory exist or not?

There are special methods for this as well. You can also easily find out the length of a file:

Code Note
Files.isRegularFile(Path.of("c:\\readme.txt"));
true
Files.isDirectory(Path.of("c:\\test"));
true
 Files.exists(Path.of("c:\\test\\1\\2\\3"));
false
Files.size(Path.of("c:\\readme.txt"));
10112

5. Working with file contents

Finally, there are a whole series of methods that make it easy to read or write the contents of a file. Example:

Code Description
Path path = Path.of("c:\\readme.txt");
List<String> list = Files.readAllLines(path);

for (String str : list)
   System.out.println(str);

Read the contents of the file as a list of strings.

Display the strings


6. Getting the contents of a directory

The most interesting method still remains. It is used to get files and subdirectories in a given directory.

We are talking about the newDirectoryStream() method, which returns a special DirectoryStream<Path> object. It has an iterator(!) that you can use to get all the files and subdirectories of a given directory.

This is easier than it sounds.

Code Description
Path path = Path.of("c:\\windows");

try (DirectoryStream<Path> files = Files.newDirectoryStream(path)) {
   for (Path path : files)
      System.out.println(path);
}


Get an object with a list of files
Loop over the list of files

The DirectoryStream<Path> object has two properties. First, it has an iterator that returns file paths, and we can use this object inside a for-each loop.

And second, this object is a data stream, so it must be explicitly closed using the close() method, or declared use inside a try-with-resources block.



7. Files.newInputStream method

Starting with Java 5, the FileInputStream and FileOutputStream classes have been deprecated. One of their disadvantages was that when objects of these classes are created, files are immediately created on disk. And all exceptions related to file creation could potentially be thrown.

Later this was recognized as not the best decision. Accordingly, it is recommended to use the methods of the java.nio.Files utility class to create file objects.

Here's a comparison between the old approach and the new approach to creating files:

Before
String src = "c:\\projects\\log.txt";
InputStream input = new FileInputStream(src);
After
String src = "c:\\projects\\log.txt";
InputStream input = Files.newInputStream( Path.of(src) );

And there is a similar replacement for FileOutputStream:

Before
String src = "c:\\projects\\log.txt";
OutputStream  output = new FileOutputStream( src );
After
String src = "c:\\projects\\log.txt";
OutputStream  output = Files.newOutputStream( Path.of( src ) );