-
Notifications
You must be signed in to change notification settings - Fork 4
Java Create File with Files.createFile()
Ramesh Fadatare edited this page Jul 11, 2019
·
1 revision
Java 7 introduced Files, which consists exclusively of static methods that operate on files, directories, or other types of files. Its createFile() method creates a new and empty file, failing if the file already exists.
The example creates a new, empty file with Files.
import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class JavaCreateFileEx3 {
public static void main(String[] args) throws IOException {
Path path = Paths.get("src/main/resources/myfile.txt");
try {
Files.createFile(path);
} catch (FileAlreadyExistsException ex) {
System.err.println("File already exists");
}
}
}
A Path object is created. It is used to locate a file in a file system:
Path path = Paths.get("src/main/resources/myfile.txt");
The new file is created with Files.createFile():
Files.createFile(path);
FileAlreadyExistsException is thrown if the file already exists:
} catch (FileAlreadyExistsException ex) {