Java Create Files

πŸ“ Java Create Files

Java provides multiple ways to create a file using:

  • java.io.File

  • java.nio.file.Files (new and preferred method from Java 7+)


βœ… 1. Creating a File Using File Class

The createNewFile() method creates a new file if it doesn’t already exist.

import java.io.File;
import java.io.IOException;
public class CreateFileExample {
public static void main(String[] args) {
try {
File file = new File(“example.txt”);

if (file.createNewFile()) {
System.out.println(“File created: “ + file.getName());
} else {
System.out.println(“File already exists.”);
}
} catch (IOException e) {
System.out.println(“An error occurred while creating the file.”);
}
}
}

Output Example:

File created: example.txt

⚠️ Note

  • The file is created in the project root directory unless a full path is provided.

Example with a path:

File file = new File("C:\\Users\\Admin\\Documents\\data.txt");

βœ… 2. Creating a File Using Files.createFile() (Better & Modern)

This approach is shorter and uses the NIO package, which is recommended for modern applications.

import java.nio.file.*;

public class CreateFileNio {
public static void main(String[] args) {
try {
Path path = Paths.get(“nioFile.txt”);
Files.createFile(path);
System.out.println(“File created successfully.”);
} catch (FileAlreadyExistsException e) {
System.out.println(“File already exists.”);
} catch (Exception e) {
System.out.println(“Error occurred.”);
}
}
}


βœ… 3. Creating a File and Writing Content Immediately

You can create and write to a file using FileWriter.

import java.io.FileWriter;
import java.io.IOException;
public class CreateAndWriteFile {
public static void main(String[] args) {
try {
FileWriter writer = new FileWriter(“notes.txt”);
writer.write(“This file was created and written using Java!”);
writer.close();
System.out.println(“File created and content written.”);
} catch (IOException e) {
System.out.println(“Error occurred.”);
}
}
}


πŸ—‚οΈ Creating Files in a Folder

If the folder does not exist, you must create it first.

import java.io.File;
import java.io.IOException;
public class CreateFileInFolder {
public static void main(String[] args) {
try {
File folder = new File(“MyFolder”);
folder.mkdir(); // create folder if not exists

File file = new File(“MyFolder/info.txt”);
file.createNewFile();

System.out.println(“File created inside folder.”);
} catch (IOException e) {
System.out.println(“Error occurred.”);
}
}
}


🧠 Summary Table

Method Package Recommended
File.createNewFile() java.io βœ” Good
Files.createFile() java.nio ⭐ Best (Modern)
FileWriter java.io Used for writing + creating

βœ” Best Practice

For modern applications:

➑ Use java.nio.file.Files because it provides:

  • Better exception handling

  • More flexible file operations

  • Improved performance

You may also like...