In this source code example, we show you how to create a file in Java.
We use Files.createFile() method to create a file in Java.
Files.createFile() Method
Creates a new and empty file, failing if the file already exists. The check for the existence of the file and the creation of the new file if it does not exist are a single operation that is atomic with respect to all other filesystem activities that might affect the directory.
Java Create File Example
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.FileAttribute;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.HashSet;
import java.util.Set;
public class JavaCreateFile {
public static void main(String[] args) throws IOException {
Set<PosixFilePermission> perms = new HashSet<>();
perms.add(PosixFilePermission.OWNER_READ);
perms.add(PosixFilePermission.OWNER_WRITE);
perms.add(PosixFilePermission.GROUP_READ);
perms.add(PosixFilePermission.GROUP_WRITE);
perms.add(PosixFilePermission.OTHERS_READ);
FileAttribute<Set<PosixFilePermission>> attrs = PosixFilePermissions.asFileAttribute(perms);
Path myPath = Paths.get("src/resources/sample.txt");
if (Files.exists(myPath)) {
System.out.println("File already exists");
} else {
Files.createFile(myPath, attrs);
System.out.println("File created");
}
}
}
Create a new file named "sample.txt" if the file does not exist:
if (Files.exists(myPath)) {
System.out.println("File already exists");
} else {
Files.createFile(myPath, attrs);
System.out.println("File created");
}
References
Related Java NIO Files Examples
- Java File Copy Example
- Java Create File Example
- Java Delete File Example
- Java File Size Example
- Java Get File Owner Example
- Java File Move Example
- Java Read File Example
- Java Write File Example
- Java Create Directory Example
- Java Create Multiple Directories Example
- Java List All Subdirectories From a Directory Example
- Java Append to File Example
Comments
Post a Comment