Java Reference
In-Depth Information
The
createDirectory()
and
createDirectories()
methods are used to create a new directory. If the parent
directory of the new directory does not exist, the
createDirectory()
method fails. The
createDirectories()
method
creates a non-existent parent directory. You can use the
createTempDirectory()
and
createTempFile()
methods to
create a temporary directory and a temporary file respectively.
The following snippet of code shows how to create temporary files and directories. The output was generated
when the program was run on Windows 7. The name generation for a temporary directory/file is implementation
dependent. Attempts are made to use the supplied prefix and suffix for the temporary file/directory. You will need to
change the paths to conform to your platform and you may get a different output.
try {
String dirPrefix = "KDir";
Path tDir = Files.createTempDirectory(dirPrefix);
System.out.println("Temp directory: " + tDir);
String fPrefix = "KF_";
String fSuffix = ".txt";
Path tFile1 = Files.createTempFile(fPrefix, fSuffix);
System.out.println("Temp file1: " + tFile1);
Path p1 = Paths.get("C:\\temp");
Path tFile2 = Files.createTempFile(p1, fPrefix, fSuffix);
System.out.println("Temp file2: " + tFile2);
}
catch (IOException e) {
e.printStackTrace();
}
Temp directory: C:\Users\ksharan\AppData\Local\Temp\KDir6632178761947534022
Temp file1: C:\Users\ksharan\AppData\Local\Temp\KF_6811753793376220963.txt
Temp file2: C:\temp\KF_4190593797467345768.txt
A temporary file/directory is not automatically deleted. You may want to use the
deleteOnExit()
method of the
java.io.File
class to delete the file when the JVM exits.
Path tempFile = Files.createTempFile("myTempFile", ".txt");
// Delete the file when the JVM exits
tempFile.toFile().deleteOnExit();
Deleting Files
The
Files
class has two methods called
delete(Path p)
and
deleteIfExists(Path p)
to delete a file, a directory,
and a symbolic link.
The
delete()
method throws an exception if the deletion fails. For example, it throws a
NoSuchFileException
if
the file being deleted does not exist and throws a
DirectoryNotEmptyException
if the directory being deleted is not
empty.
The
deleteIfExists()
method does not throw a
NoSuchFileException
if the file being deleted does not exist. It
returns
true
if it deletes the file. Otherwise, it returns
false
. It throws a
DirectoryNotEmptyException
if the directory
being deleted is not empty.