0
0
JavaHow-ToBeginner · 3 min read

How to Write a File in Java: Simple Guide with Example

To write a file in Java, use FileWriter or BufferedWriter classes to open a file and write text to it. Always close the writer to save changes and avoid resource leaks.
📐

Syntax

Use FileWriter to write characters to a file. Wrap it with BufferedWriter for efficient writing. Always close the writer with close() or use try-with-resources to auto-close.

  • FileWriter(String filename): Opens or creates a file to write.
  • BufferedWriter(Writer writer): Buffers output for better performance.
  • write(String text): Writes text to the file.
  • close(): Closes the writer and saves the file.
java
try (BufferedWriter writer = new BufferedWriter(new FileWriter("filename.txt"))) {
    writer.write("Your text here");
}
💻

Example

This example writes a simple message to a file named output.txt. It uses try-with-resources to automatically close the writer.

java
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class WriteFileExample {
    public static void main(String[] args) {
        String text = "Hello, this is a file write example in Java.";
        try (BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"))) {
            writer.write(text);
            System.out.println("File written successfully.");
        } catch (IOException e) {
            System.err.println("Error writing file: " + e.getMessage());
        }
    }
}
Output
File written successfully.
⚠️

Common Pitfalls

Common mistakes when writing files in Java include:

  • Not closing the writer, which can cause data loss.
  • Ignoring exceptions that may occur during writing.
  • Using FileWriter without buffering, which can be slower.
  • Overwriting files unintentionally without appending.

Use try-with-resources to ensure closing and handle exceptions properly.

java
/* Wrong way: Not closing writer and ignoring exceptions */
import java.io.FileWriter;

public class WrongWrite {
    public static void main(String[] args) throws Exception {
        FileWriter writer = new FileWriter("file.txt");
        writer.write("Hello");
        // Missing writer.close();
    }
}

/* Right way: Using try-with-resources to auto-close and handle exceptions */
import java.io.FileWriter;
import java.io.IOException;

public class RightWrite {
    public static void main(String[] args) {
        try (FileWriter writer = new FileWriter("file.txt")) {
            writer.write("Hello");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
📊

Quick Reference

Class/MethodPurpose
FileWriter(String filename)Creates or opens a file for writing characters
BufferedWriter(Writer writer)Buffers writes for better performance
write(String text)Writes text to the file
close()Closes the writer and saves the file
try-with-resourcesAutomatically closes writers to prevent leaks

Key Takeaways

Use FileWriter and BufferedWriter to write text files efficiently in Java.
Always close your writer using try-with-resources to save data and free resources.
Handle IOException to catch errors during file writing.
BufferedWriter improves performance by reducing disk writes.
Be careful to not overwrite files unless intended; use append mode if needed.