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()); } } }
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.