Java Create Files

Java Create Files

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.


1. Using java.io.File.createNewFile()

The createNewFile() method of the java.io.File class is the classic way to create a file.

Because it can throw a checked exception, you must handle it with a try...catch block.

Using `createNewFile()`

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


2. Using 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.

Using `Files.createFile()`

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 FileWriter and FileOutputStream will 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.