Java Program to Create File and Write to the File

In this java program, we will learn about creating a file and deleting a file. In Java, you can create a new file and write to it using the File class and the FileWriter class.

The File class is used to represent a file or directory in the file system, while the FileWriter class is used to write characters to a file.

Here is an example of how you can create a new file and write to it in Java.

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class FileCreationExample {
  public static void main(String[] args) {
    try {
      String fileName = "example.txt";
      File file = new File(fileName);
      // creates the file
      file.createNewFile();
      FileWriter writer = new FileWriter(file);
      writer.write("Hello World!");
      writer.close();
      System.out.println("File created and" +
              " written to successfully!");
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
Output
File created and written to successfully!

In this example, the main method creates a new File object with the file name "example.txt" and then calls the createNewFile() method to create the file. Then, it creates a FileWriter object and uses it to write the string "Hello World!" to the file. Finally, the FileWriter object is closed and a message is printed to the console to indicate that the file was created and written to successfully.

It's important to note that the createNewFile() method will throw an IOException if the file already exists or if the file cannot be created for some reason. That's why the code is wrapped in a try-catch block to handle the exception.

Also, FileWriter class has a overloaded version of constructor which accepts second boolean parameter append, if the value of this parameter is true, the data will be written to the end of file and if the file does not exist, it creates a new file. If the parameter is false, it will overwrite the existing file and create a new file if the file doesn't exist.

Here are a few more things to keep in mind when creating and writing to a file in Java.
  • When creating a new file, you can specify the file path as well as the file name. For example, File file = new File("/path/to/file/example.txt") creates a new file called "example.txt" in the "/path/to/file" directory.

  • If you want to write to a file that already exists, you can use the FileWriter(file, true) constructor, where the second parameter is a boolean value that indicates whether to append to the file or overwrite it.

  • You can also use the Files.write() method from the java.nio.file package to write to a file. This method has several overloads that allow you to write a String, byte array, or a list of strings to a file.

  • Always make sure to close the FileWriter or any other stream after you're done using it, this will release the resources associated with it and also it's a good practice.