🔥Limited Offer: Get 50% OFFon AI & Full Stack Courses🔥
Back to Java Notes
Topic #89

Java Create Files


Create a File

In Java, you can create a new file with the createNewFile() method from the File class.

This method returns:

  • true - if the file was created successfully
  • false - if the file already exists

Note that the method is enclosed in a try...catch block. This is necessary because it throws an IOException if an error occurs (if the file cannot be created for some reason):

Example

import java.io.File;       // Import the File class
import java.io.IOException; // Import IOException to handle errors

public class CreateFile {
  public static void main(String[] args) {
    try {
      File myObj = new File("filename.txt"); // Create File object
      if (myObj.createNewFile()) {           // Try to create the file
        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(); // Print error details
    }
  }
}

Explanation: The program tries to create a file called filename.txt. If the file does not exist, it will be created and a success message is printed. If the file already exists, you will see the message "File already exists." instead.

Note: The createNewFile() method only creates an empty file. It does not add any content inside. You will learn how to write text to files in the next chapter.


Create a File in a Specific Folder

To create a file in a specific directory (requires permission), specify the path of the file and use double backslashes to escape the "\" character (for Windows). On Mac and Linux you can just write the path, like: /Users/name/filename.txt

Example

File myObj = new File("C:\\Users\\MyName\\filename.txt");

Want to go beyond the notes?

Join CodingNow 2.0's Java course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

Java Create Files – FAQs

Quick answers about learning Java Create Files in Java.

This free note from CodingNow 2.0 explains Java Create Files in Java — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every Java topic on CodingNow 2.0, including Java Create Files, is 100% free with no signup required.
With focused practice, most students grasp Java Create Files in 1–3 days from these notes; pairing it with CodingNow 2.0's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the CodingNow 2.0 Community (/community) — expert instructors answer within 24 hours.
WhatsApp
Call NowEnroll Now