How to Write to a File in Java: 6 Ways with Examples
Saving data is as important as reading it: exporting reports, storing settings and generating documents all mean writing to a file. Java gives you several ways to do it, from one-line helpers to fully controlled streams.
This tutorial shows every common way to write a file in Java 25, each with a complete, tested example.
1. What Is Writing to a File in Java?
Writing to a file means opening it for output, converting your data to bytes (for text, by encoding characters with a charset) and saving them. By default, every method on this page creates the file if it is missing and replaces its content if it exists. To keep existing content, see How to Append to a File.
2. Ways to Write a File at a Glance
| Way | Writes | Best for | Since |
|---|---|---|---|
Files.writeString() | A String | Small text content | Java 11 |
Files.write(path, lines) | A list of lines | Collections of lines | Java 7 (UTF-8 overload Java 8) |
BufferedWriter | Text, piece by piece | Large or generated output | Java 1.1 |
FileWriter | Characters | Simple classic code | Java 1.1 (charset Java 11) |
PrintWriter | Formatted text | Reports with printf | Java 1.1 |
Files.write(path, bytes) / FileOutputStream | Bytes | Binary files | Java 7 / 1.0 |
3. Using Files.writeString()
One call writes a whole string to a file.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class WriteWithWriteString {
public static void main(String[] args) throws IOException {
Path welcome = Files.createTempFile("welcome", ".txt");
Files.writeString(welcome, "Welcome to the library!\nOpen 9 AM to 6 PM.\n"); // Java 11
System.out.print(Files.readString(welcome));
Files.delete(welcome);
}
}
Welcome to the library! Open 9 AM to 6 PM.
How it works
Files.writeString()(Java 11) encodes the text as UTF-8.- With no options, it creates the file or replaces its content.
4. Using Files.write() with Lines
When your data is already a list, Files.write() writes one element per line.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
public class WriteLines {
public static void main(String[] args) throws IOException {
Path menu = Files.createTempFile("menu", ".txt");
List<String> dishes = List.of("Paneer tikka", "Dal makhani", "Jeera rice");
Files.write(menu, dishes); // one element per line, UTF-8
System.out.println("Lines written: " + Files.readAllLines(menu).size());
Files.delete(menu);
}
}
Lines written: 3
How it works
- Each element is followed by the platform line separator.
- The text is encoded as UTF-8.
5. Using BufferedWriter
For many small writes, BufferedWriter collects text in memory and writes it in blocks.
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class WriteWithBufferedWriter {
public static void main(String[] args) throws IOException {
Path table = Files.createTempFile("table", ".txt");
try (BufferedWriter out = Files.newBufferedWriter(table)) { // UTF-8, buffered
for (int i = 1; i <= 10; i++) {
out.write("7 x " + i + " = " + (7 * i));
out.newLine();
}
}
System.out.println("Last line: " + Files.readAllLines(table).getLast());
Files.delete(table);
}
}
Last line: 7 x 10 = 70
How it works
Files.newBufferedWriter()returns a UTF-8BufferedWriter.newLine()ends each line with the platform separator.- Closing the writer flushes the remaining text.
6. Using FileWriter
FileWriter is the classic java.io way to write text.
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
public class WriteWithFileWriter {
public static void main(String[] args) throws IOException {
Path reminder = Files.createTempFile("reminder", ".txt");
try (FileWriter out = new FileWriter(reminder.toFile(), StandardCharsets.UTF_8)) { // Java 11
out.write("Renew car insurance before 30 Nov.\n");
}
System.out.print(Files.readString(reminder));
Files.delete(reminder);
}
}
Renew car insurance before 30 Nov.
How it works
- The constructor with a
Charset(Java 11) makes the encoding explicit. - Try-with-resources closes and flushes the writer.
7. Using PrintWriter
PrintWriter adds println() and printf() for formatted output.
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Locale;
public class WriteWithPrintWriter {
public static void main(String[] args) throws IOException {
Path bill = Files.createTempFile("bill", ".txt");
try (PrintWriter out = new PrintWriter(bill.toFile(), StandardCharsets.UTF_8)) { // Java 10
out.printf(Locale.ROOT, "%-8s %7.2f%n", "Coffee", 180.0);
out.printf(Locale.ROOT, "%-8s %7.2f%n", "Sandwich", 245.5);
}
System.out.print(Files.readString(bill));
Files.delete(bill);
}
}
Coffee 180.00 Sandwich 245.50
How it works
%-8sleft-aligns text and%7.2fright-aligns numbers with two decimals.Locale.ROOTkeeps the decimal point as.on every computer.
8. Writing Binary Data
Binary data such as sensor readings or images is written as bytes.
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class WriteBytes {
public static void main(String[] args) throws IOException {
Path data = Files.createTempFile("sensor", ".bin");
byte[] readings = {18, 19, 21, 24, 22};
Files.write(data, readings); // whole array in one call
System.out.println("Size after Files.write: " + Files.size(data));
try (FileOutputStream out = new FileOutputStream(data.toFile())) { // classic stream
out.write(readings, 0, 3); // only the first three bytes
}
System.out.println("Size after FileOutputStream: " + Files.size(data));
Files.delete(data);
}
}
Size after Files.write: 5 Size after FileOutputStream: 3
How it works
Files.write(path, bytes)writes the whole array in one call.FileOutputStream.write(array, 0, 3)writes part of an array and, without append mode, replaces the previous content.
9. Common Mistakes and Best Practices
- Overwriting data by accident. All these methods replace existing content unless you append.
- Forgetting to close writers. Buffered text is lost; use try-with-resources.
- Relying on the default charset in older code. Specify UTF-8 for
FileWriterandPrintWriter. - Writing to a missing folder. Create it first with
Files.createDirectories(). - Writing large output with string concatenation. Stream it through a
BufferedWriter.
10. Summary
Files.writeString()andFiles.write()cover most simple cases in one line.- Use
BufferedWriterfor large or generated output. - Use
PrintWriterfor formatted text andFileWriterin classic code. - Write binary data with
Files.write(path, bytes)orFileOutputStream. - Writing replaces content by default; use append mode to keep it.