The java.nio.files.Files
class brings with it many of these new Features and facilities.
In case of the need to create one or more directories, let's see how the static methods Files.createDirectory(Path)
and Files.createDirectories(Path)
work.
How do we create a directory using such resources?
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Main {
public static void main(String[] args) {
Path path = Paths
.get("/home/user/Documents/directoryCreatedFromJavaApp2");
try {
Files.createDirectory(path);
} catch (IOException e) {
e.printStackTrace();
}
}
}
In the class above, we are first using the class Path
, which represents the path - path - to the directory file we want to create. We get an instance of it from the call to the static fabrication method that is in the Paths
class. We define through the method Paths.get(String)
- through String
passed as parameter, which is the directory we want to create.
... createDirectory(Path)
- non-singular
Exactly, here is an important detail. This method creates only one directory, the last one in our String
: /home/user/Documents/directoryCreatedFromJavaApp2
That is, we created the directoryCreatedFromJavaApp2
directory here.
So the directories before this should already exist?
Exactly, if they do not exist, the method will throw java.nio.file.NoSuchFileException
indicating the non-existence of the previous path, which leads us to have to catch IOException
(we can also only propagate the exception depending on our design).
What if the directory I'm creating already exists?
In this case the Files.createDirectory(Path)
method throws an exception: java.nio.file.FileAlreadyExistsException
, so the need to continue capturing IOException
- FileAlreadyExistsException
superclass.
How do we create directories using such resources?
So now, we'll see the Files.createDirectories(Path)
method.
Let's look at an example:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Main {
public static void main(String[] args) {
Path path = Paths
.get("/home/user/Documents/directory1/directory2/directory3");
try {
Files.createDirectories(path);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Again, we noticed in the above code that we had to use a Path
object. In fact the only difference was in the method for directory creation, in our case ... directories in the plural. Now an important point, unlike the previous method, this method does not require that the parent directories of the last directory exist, because if they do not exist, they will be created.
What if the directory already exists when we call Files.createDirectories(Path)
?
No exception will be thrown, nothing will actually happen with the directory
For more details consult the Javadocs: link