Java Reference
In-Depth Information
ception
must be last, because the other two exception types are derived from
IOException
. The output
shows that when this method is called for the relative path,
relPath
, the first time around the directory is
created and the second time
FileAlreadyExistsException
is thrown, as you would expect. Calling the
method for the absolute path,
absPath
, causes
NoSuchFileException
to be thrown because the parent
path does not exist. Since the actions are the same for both, you catch either of them as type
IOExcep-
tion
in a single catch block.
The
createMultipleDirectories()
method calls the static
createDirectories()
method in the
Files
class. The
createDirectories()
method creates all the directories required for the path and
therefore the directory specified by
absPath
is created when
createMultipleDirectories()
is called.
The second time the method is called, no exception is thrown. If the directory that is specified by
the
Path
object that is passed to
createDirectories()
already exists, the method does nothing.
FileAlreadyExistsException
is thrown only when there is a file or symbolic link with the same name
as the requested directory already in existence.
Creating Files
To create a new empty file you can call the static
createFile()
method in the
Files
class with the
Path
object that specifies the file path as the argument. If the file already exists, the
FileAlreadyExistsExcep-
tion
exception is thrown by the method. The method also throws an exception of type
IOException
if an
I/O error occurs. Note that the parent directory for the new file must exist before you create the file. The
createFile()
method throws an exception of type
java.nio.file.NoSuchFileException
if the parent
directory does not exist. Here's an example:
Path path = Paths.get("D:/Garbage/dir/dir1/dir2/junk.txt");
try {
Files.createFile(path);
} catch(NoSuchFileException e) {
System.err.println("File not created.\n" + e);
} catch(FileAlreadyExistsException e) {
System.err.println("File not created.\n" + e);
} catch(IOException e) {
System.err.println(e);
}
The fragment above creates the file with the name
junk.txt
in the
dir2
directory. If the parent directory
for the file does not exist, the exception of type
NoSuchFileException
is thrown and caught in this case.
Of course, you could always ensure that the parent directory exists, like this:
Path path = Paths.get("D:/Garbage/dir/dir1/dir2/junk.txt");
try {
Files.createDirectories(path.getParent()); // Create parent
Files.createFile(path);
} catch(FileAlreadyExistsException e) {
System.err.println("File not created.\n" + e);
} catch(IOException e) {
System.err.println(e);
}