Creates a new and empty file, failing if the file already exists.

package com.logicbig.example.files;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class CreateFileExample {
public static void main(String... args) throws IOException {
Path dir = Files.createTempDirectory("my-dir");
Path fileToCreatePath = dir.resolve("test-file.txt");
System.out.println("File to create path: " + fileToCreatePath);
Path newFilePath = Files.createFile(fileToCreatePath);
System.out.println("New file created: " + newFilePath);
System.out.println("New File exits: " + Files.exists(newFilePath));
}
}
Output
File to create path: C:\Users\Joe\AppData\Local\Temp\my-dir495841472124666354\test-file.txt
New file created: C:\Users\Joe\AppData\Local\Temp\my-dir495841472124666354\test-file.txt
New File exits: true
Attempting to create file which already exits:

package com.logicbig.example.files;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class CreateFileExample2 {
public static void main(String... args) throws IOException {
Path dir = Files.createTempDirectory("my-dir");
Path fileToCreatePath = dir.resolve("test-file.txt");
Path newFilePath = Files.createFile(fileToCreatePath);
//creating same file again
Path newFilePath2 = Files.createFile(newFilePath);
}
}
Output
java.nio.file.FileAlreadyExistsException: C:\Users\Joe\AppData\Local\Temp\my-dir3718395074989233340\test-file.txt
at sun.nio.fs.WindowsException.translateToIOException (WindowsException.java:81)
at sun.nio.fs.WindowsException.rethrowAsIOException (WindowsException.java:97)
at sun.nio.fs.WindowsException.rethrowAsIOException (WindowsException.java:102)
at sun.nio.fs.WindowsFileSystemProvider.newByteChannel (WindowsFileSystemProvider.java:230)
at java.nio.file.Files.newByteChannel (Files.java:361)
at java.nio.file.Files.createFile (Files.java:632)
at com.logicbig.example.files.CreateFileExample2.main (CreateFileExample2.java:20)