Java Write to Files
gocourse.in Maintenance

We'll be back soon

Our CDN (cdn.gocourse.in) is currently unreachable. Some images, JavaScript, or CSS files may not load properly.

Estimated downtime: ~30 minutes

Java Write to Files

Harine

Java Write to Files

Writing Data to a File in Java

Writing data to files is a common requirement in many Java applications. Programs often need
to store logs, save user data, generate reports, or export information. Java provides several
classes for writing data to files, and one of the simplest options for beginners is the FileWriter
class.

The FileWriter class allows you to create a file and write character-based data into it. The write()
method is used to insert text into the file.

When working with file operations, it is important to handle exceptions such as IOException
because file writing may fail due to permission issues, incorrect file paths, or other
system-related errors.

Example: Writing Text to a File

The following program demonstrates how to write text into a file named notes.txt using the
FileWriter class.

import java.io.FileWriter;
import java.io.IOException;
public class FileWriteExample {
  public static void main(String[] args) {
    try {
        FileWriter writer = new FileWriter("notes.txt");
        writer.write("Learning Java file handling is essential for real-world applications.\n");
        writer.write("This file was created and written using FileWriter.");
        writer.close(); // close the writer manually
        System.out.println("Data written to file successfully.");
} catch (IOException error) {
        System.out.println("Error occurred while writing to the file.");
        error.printStackTrace();
     }
   }
 }

Sample Output

Data written to file successfully.

Explanation

  1. The program imports the FileWriter class to write text to a file.
  2. A FileWriter object is created for the file notes.txt.
  3. The write() method inserts text into the file.
  4. The close() method releases system resources and ensures the data is properly saved.
  5. If an error occurs, the catch block handles the exception and prints the error details.

Writing Files Using Try-With-Resources

Starting from Java 7, the try-with-resources statement was introduced. This feature
automatically closes resources such as file writers, reducing the risk of resource leaks.

Using this approach eliminates the need to manually call the close() method.

import java.io.FileWriter;
import java.io.IOException;
public class AutoCloseFileWriter {
  public static void main(String[] args) {
    try (FileWriter writer = new FileWriter("log.txt")) {
        writer.write("Application started successfully.\n");
        writer.write("System log generated using try-with-resources.");
        System.out.println("File written successfully.");
    } catch (IOException error) {
        System.out.println("Unable to write to the file.");
        error.printStackTrace();
      }
    }
 }

Output

File written successfully.

Why Use Try-With-Resources?

  • Automatically closes file resources
  • Reduces boilerplate code
  • Prevents resource leaks
  • Improves code readability

Appending Data to an Existing File

By default, FileWriter overwrites the existing file content. If you want to add new content without
deleting the existing data, you must enable append mode.

This can be done by using the two-argument constructor of FileWriter and passing true as the
second parameter.

import java.io.FileWriter;
import java.io.IOException;
public class FileAppendExample {
  public static void main(String[] args) {
    try (FileWriter writer = new FileWriter("notes.txt", true)) {
        writer.write("\nNew entry: File handling practice completed.");
        System.out.println("Content appended successfully.");
    } catch (IOException error) {
        System.out.println("Failed to append data.");
        error.printStackTrace();
      }
    }
  }

Output

Content appended successfully.

Explanation

In this example:

  • The file notes.txt is opened in append mode.
  • New text is added to the end of the file instead of replacing the existing content.
  • If the file does not exist, Java will automatically create it.

Tags
Our website uses cookies to enhance your experience. Learn More
Accept !