To create a new, empty file in Java, you can use methods from both the traditional java.io package and the modern java.nio package.
java.io.File.createNewFile()The createNewFile() method of the java.io.File class is the classic way to create a file.
true if the file was created successfully.false if the file already exists.IOException if an I/O error occurred.Because it can throw a checked exception, you must handle it with a try...catch block.
import java.io.File; import java.io.IOException;public class Main { public static void main(String[] args) { try { File myObj = new File("filename.txt"); if (myObj.createNewFile()) { System.out.println("File created: " + myObj.getName()); } else { System.out.println("File already exists."); } } catch (IOException e) { System.out.println("An error occurred."); e.printStackTrace(); } } }
java.nio.file.Files.createFile()The modern approach uses the Files utility class from the NIO.2 API. This method is generally preferred in new code.
Path to the newly created file.FileAlreadyExistsException if the file is already there, which is more specific and often more useful than the false return from the old API.import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths;public class Main { public static void main(String[] args) { Path path = Paths.get("newfile.txt"); try { Path createdFile = Files.createFile(path); System.out.println("File created at: " + createdFile.toAbsolutePath()); } catch (IOException e) { System.err.println("Error creating file: " + e.getMessage()); } } }
Sometimes your application needs to store transient data that shouldn't be kept permanently. Java provides a convenient way to create temporary files that are typically stored in the default temporary-file directory of your operating system.
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path;public class Main { public static void main(String[] args) { try { // Creates a temporary file with a specified prefix and suffix (.tmp by default if null) Path tempFile = Files.createTempFile("myApp-", ".log"); System.out.println("Temporary file created at: " + tempFile.toAbsolutePath()); // Request the file to be deleted when the JVM terminates tempFile.toFile().deleteOnExit(); } catch (IOException e) { System.err.println("Error creating temp file: " + e.getMessage()); } } }
Pro Tip: Calling
deleteOnExit()is a common practice to ensure the temporary file is automatically cleaned up when your Java program finishes running.
When using the modern java.nio.file.Files API, you can define specific file attributes, such as read/write/execute permissions, at the exact moment of file creation. This is particularly useful on POSIX-compliant file systems (like Linux and macOS).
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.Set;public class Main { public static void main(String[] args) { Path path = Paths.get("secure-file.txt"); try { // Define permissions: Owner can read/write, others have no access (rw-------) Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rw-------"); FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions.asFileAttribute(perms); Path createdFile = Files.createFile(path, attr); System.out.println("Secure file created at: " + createdFile.toAbsolutePath()); } catch (UnsupportedOperationException e) { System.err.println("POSIX file permissions are not supported on this OS."); } catch (IOException e) { System.err.println("Error creating file: " + e.getMessage()); } } }
Note: Other classes like
FileWriterandFileOutputStreamwill also create a file if it doesn't exist when you try to open it for writing. We will cover this in the next chapter.
Which modern Java class provides the `createFile()` method?