Java Write to Files

Java Write to Files

To write content to a file in Java, you typically use one of the Writer classes. The most common one for writing text is java.io.FileWriter.


Using FileWriter

The FileWriter class is used to write character streams to a file. When you create a FileWriter object, it will automatically create the file if it doesn't exist.

By default, FileWriter will overwrite the existing content of the file.

Writing to a File

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

public class Main { public static void main(String[] args) { try { FileWriter myWriter = new FileWriter("filename.txt"); myWriter.write("Files in Java might be tricky, but it is fun enough!"); myWriter.close(); // Important: close the writer to save changes System.out.println("Successfully wrote to the file."); } catch (IOException e) { System.out.println("An error occurred."); e.printStackTrace(); } } }

Important: You must call the close() method on the writer when you are finished. If you don't, the data might not be saved correctly to the file.


The try-with-resources Statement

Forgetting to close a file writer is a common mistake that can lead to resource leaks. Since Java 7, there is a much better way to handle resources like file streams: the try-with-resources statement.

It automatically closes the resource for you when the try block is finished, even if an error occurs.

Using `try-with-resources`

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

public class Main { public static void main(String[] args) { // The FileWriter is declared inside the try parentheses try (FileWriter myWriter = new FileWriter("modern-file.txt")) { myWriter.write("This is the modern, safe way to write files."); System.out.println("Successfully wrote to the file."); } catch (IOException e) { System.out.println("An error occurred: " + e.getMessage()); } // myWriter is automatically closed here! } }


Appending to a File

If you want to add content to the end of an existing file instead of overwriting it, you can pass a second, boolean argument (true) to the FileWriter constructor.

Appending to a File

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

public class Main { public static void main(String[] args) { // The 'true' parameter enables append mode try (FileWriter myWriter = new FileWriter("filename.txt", true)) { myWriter.write("\nThis text will be appended to the end."); System.out.println("Successfully appended to the file."); } catch (IOException e) { System.out.println("An error occurred."); } } }

For better performance when writing large amounts of text, you can wrap your FileWriter in a BufferedWriter.