Java Programs›File Handling›Write to a File

Write to a File in Java

beginner·  File Handling  ·  File I/O

Problem

Writing a file means opening an output stream to it, sending characters, and closing it; a BufferedWriter collects characters in memory and writes them in larger, more efficient chunks.

Create a text file containing three to-do items, one per line, then read the file back to show what was written.

Input
Buy milk, Call the bank, Finish the report
Output
notes.txt with 3 lines

Java Program

Java
import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class WriteToFile { public static void main(String[] args) throws IOException { Path file = Paths.get("notes.txt"); try (BufferedWriter writer = new BufferedWriter(new FileWriter(file.toFile()))) { // closed automatically writer.write("Buy milk"); writer.newLine(); // the platform's line separator writer.write("Call the bank"); writer.newLine(); writer.write("Finish the report"); } System.out.println("Wrote " + Files.readAllLines(file).size() + " lines to " + file); System.out.println("File contents:"); for (String line : Files.readAllLines(file)) { System.out.println(" " + line); } Files.delete(file); // tidy up the demo file } }

Output

Wrote 3 lines to notes.txt File contents: Buy milk Call the bank Finish the report

Core Logic

A BufferedWriter wrapped around a FileWriter handles the writing, and try-with-resources guarantees the file is flushed and closed.

How It Works
  1. 1new FileWriter(file.toFile()) creates notes.txt, or empties it if it already exists.
  2. 2writer.write(...) sends each item, and newLine() adds the operating system's line separator.
  3. 3Leaving the try block closes the writer, which flushes any buffered text to disk.
  4. 4Files.readAllLines reads the file back to prove the content arrived, then the demo file is deleted.
Three write calls and two newLine calls produce a three-line file.
💡

Key Point: If a writer is never closed, the last buffered characters may never reach the disk — which is why try-with-resources is the standard pattern.

Key Concepts

FileWriterBufferedWritertry-with-resourcesnewLine()

Approach 2: Using Files.writeString() and Files.write()

Java
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.List; public class WriteToFileNio { public static void main(String[] args) throws IOException { Path file = Paths.get("notes.txt"); Files.writeString(file, "A single string, written in one call\n"); // Java 11+ System.out.print("After writeString: " + Files.readString(file)); List<String> lines = Arrays.asList("line one", "line two"); Files.write(file, lines); // replaces the old contents, one element per line System.out.println("After write(lines): " + Files.readAllLines(file)); Files.delete(file); } }

Output

After writeString: A single string, written in one call After write(lines): [line one, line two]

Core Logic

The java.nio.file.Files helpers open, write and close the file in a single call.

How It Works
  1. 1Files.writeString(file, text) (Java 11+) writes one string in UTF-8.
  2. 2Files.write(file, lines) writes a list, one element per line, replacing the previous contents.
  3. 3Files.readString and Files.readAllLines read the results back.
The second call overwrites the first, so the file ends up holding just line one and line two.
💡

Key Point: These helpers are perfect for small files; use a BufferedWriter when writing large amounts of data incrementally.

Key Concepts

Files.writeString()Files.write()java.nio.file

Interview Questions

Does FileWriter overwrite an existing file?

Yes, by default it truncates the file. Pass true as the second argument to append instead.

Why use BufferedWriter rather than FileWriter alone?

Buffering collects characters in memory and writes them in larger chunks, which is much faster than many small writes.

Learn the Concept

Related Programs