Java

How to Create/Write a File in Java?

Java provides a predefined class named “File” which can be found in the java.io package. The File class assists us in working with the files as it provides a wide range of methods such as mkdir(), getName(), and many more. If we talk about file creation and writing to the file, the createNewFile(), and write() methods of the File and FileWriter classes can be used respectively.

This write-up provides a profound understanding of the following concepts:

  • How to Create a File in Java
  • How to Write Data to a File in Java
  • Practical Implementation of createNewFile() and write() methods

So let’s start!

How to Create a File in Java

The file class provides a createNewFile() method that makes it possible to create an empty file and if a file is created successfully then it returns true, and if the file already exists then we will get a false value.

Example
The below-given code imports two classes: File and IOException of the java.io package:

package filehandlingexample;
import java.io.File;
import java.io.IOException;

public class FileCreationExample {
    public static void main(String[] args) {
        try {
            File newFile= new File("C:JavaFile.txt");
            if (newFile.createNewFile()) {
                System.out.println("File created: " + newFile.getName());
            } else {
                System.out.println("File Already Exists");
            }
        } catch (IOException excep) {
            System.out.println("Error");
            excep.printStackTrace();
        }
    }
}

To create a file, we utilize the object of the File class with the createNewFile() method and the getName() method is used to get the specified name of the File. Moreover, to tackle the exceptions we utilize the try, catch statements, and within the try block, we utilize the if-else statements to handle two possibilities: file created and file already exists. While the catch block will execute to throw an exception:

The above snippet authenticates that the file created successfully.

How to Write Data to a File using write() method in Java

Java provides a built-in class FileWriter that can be used to write data to any file and to do so, the FileWriter() class provides a write() method. While working with the FileWriter class we have to utilize the close() method to close the file.

Example
Let’s consider the below code snippet that writes the data to a file:

public class FileWriteExample {
  public static void main(String[] args) {
      try {
          FileWriter fileObj = new FileWriter("JavaFile.txt");
          fileObj.write("Welcome to LinuxHint");
          fileObj.close();
          System.out.println("Data written to the file Successfully");
      } catch (IOException e) {
          System.out.println("Error");
          e.printStackTrace();
      }
  }    
}

In the above code snippet, we created an object of the FileWriter class, and within the parenthesis, we specified the file name to whom we want to write the data. Next, we utilize the write() method of the same class to write the data to the file and then close the file using the close() method. Finally, we handled the exceptions in the catch block using the IOException class.

The output validates that the write() method succeeds in writing the data to a file.

Conclusion

In java, the createNewFile(), and write() methods of File and FileWriter classes can be used respectively to create a file and to write data to a specific file. Moreover, we have to utilize the close() method when working with the FileWriter class to close the File. This write-up presents a comprehensive overview of how to create a file and how to write data to a file in java.

About the author

Anees Asghar

I am a self-motivated IT professional having more than one year of industry experience in technical writing. I am passionate about writing on the topics related to web development.