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-dir16268531677381969637\test-file.txt
New file created: C:\Users\Joe\AppData\Local\Temp\my-dir16268531677381969637\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
Caused by: java.nio.file.FileAlreadyExistsException: C:\Users\Joe\AppData\Local\Temp\my-dir5014557008358685604\test-file.txt
at java.base/sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:87)
at java.base/sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:103)
at java.base/sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:108)
at java.base/sun.nio.fs.WindowsFileSystemProvider.newByteChannel(WindowsFileSystemProvider.java:231)
at java.base/java.nio.file.Files.newByteChannel(Files.java:369)
at java.base/java.nio.file.Files.createFile(Files.java:640)
at com.logicbig.example.files.CreateFileExample2.main(CreateFileExample2.java:20)
... 6 more