Java Reference
In-Depth Information
Performing File Operations on a Path
The java.nio.file.Files class consists of all static methods that let you perform most of the file operations on a
Path object.
Creating New Files
The Files class provides several methods to create regular files, directories, symbolic links, and temporary files/
directories. These methods throw an IOException when an I/O error occurs during the file creation; for example,
they throw an IOException if you attempt to create a file that already exists. Most of the methods accept a varargs
parameter of the FileAttribute type, which lets you specify the file attributes. I will discuss file attributes shortly.
You can use the createFile() method to create a new regular file. The new file, if created, is empty. The file
creation fails in case the file already exists, or the parent directory does not exist. Listing 10-4 shows how to create
a new file. It attempts to create a text.txt file in your default directory. The program prints the details of the file
creation status.
Listing 10-4. Creating a New File
// CreateFileTest.java
package com.jdojo.nio2;
import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;
public class CreateFileTest {
public static void main(String[] args) {
Path p1 = Paths.get("test.txt");
try {
Files.createFile(p1);
System.out.format("File created: %s%n", p1.toRealPath());
}
catch (FileAlreadyExistsException e) {
System.out.format("File %s already exists.%n",
p1.normalize());
}
catch (NoSuchFileException e) {
System.out.format("Directory %s does not exists.%n",
p1.normalize().getParent());
}
catch (IOException e) {
e.printStackTrace();
}
}
}
 
Search WWH ::




Custom Search