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.
FileWriterThe 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.
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.
try-with-resources StatementForgetting 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.
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! } }
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.
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."); } } }
BufferedWriter for PerformanceFor better performance when writing large amounts of text, you should wrap your FileWriter in a BufferedWriter. A BufferedWriter writes data to an internal buffer instead of directly to the disk every time a write operation is called. Once the buffer is full, it flushes the entire chunk of data to the disk at once, significantly reducing expensive disk I/O operations.
import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException;public class Main { public static void main(String[] args) { try (BufferedWriter bw = new BufferedWriter(new FileWriter("large-file.txt"))) { bw.write("First line of text.\n"); bw.write("Second line of text.\n"); // You can also use newLine() instead of '\n' bw.newLine(); bw.write("Third line after a blank line."); System.out.println("Finished writing efficiently."); } catch (IOException e) { System.err.println("Error writing to file: " + e.getMessage()); } } }
java.nio.file.FilesSimilar to reading files, the modern java.nio.file API provides convenient, often one-liner methods for writing files. The Files.writeString() method (introduced in Java 11) is perfect for quickly writing a simple string to a file.
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption;public class Main { public static void main(String[] args) { Path path = Paths.get("nio-file.txt"); String content = "Hello from the modern NIO.2 API!\n"; try { // Write string to file, creating it if it doesn't exist, and appending if it does Files.writeString(path, content, StandardOpenOption.CREATE, StandardOpenOption.APPEND); System.out.println("Successfully wrote string to path."); } catch (IOException e) { System.err.println("Error writing file: " + e.getMessage()); } } }
How do you enable append mode when creating a `FileWriter`?