00:00

How to Write to a File in Java: 6 Ways with Examples

Last updated:

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

WayWritesBest forSince
Files.writeString()A StringSmall text contentJava 11
Files.write(path, lines)A list of linesCollections of linesJava 7 (UTF-8 overload Java 8)
BufferedWriterText, piece by pieceLarge or generated outputJava 1.1
FileWriterCharactersSimple classic codeJava 1.1 (charset Java 11)
PrintWriterFormatted textReports with printfJava 1.1
Files.write(path, bytes) / FileOutputStreamBytesBinary filesJava 7 / 1.0

3. Using Files.writeString()

One call writes a whole string to a file.

WriteWithWriteString.java
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);
    }
}
Output
Welcome to the library!
Open 9 AM to 6 PM.

How it works

  1. Files.writeString() (Java 11) encodes the text as UTF-8.
  2. 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.

WriteLines.java
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);
    }
}
Output
Lines written: 3

How it works

  1. Each element is followed by the platform line separator.
  2. The text is encoded as UTF-8.

5. Using BufferedWriter

For many small writes, BufferedWriter collects text in memory and writes it in blocks.

WriteWithBufferedWriter.java
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);
    }
}
Output
Last line: 7 x 10 = 70

How it works

  1. Files.newBufferedWriter() returns a UTF-8 BufferedWriter.
  2. newLine() ends each line with the platform separator.
  3. Closing the writer flushes the remaining text.

6. Using FileWriter

FileWriter is the classic java.io way to write text.

WriteWithFileWriter.java
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);
    }
}
Output
Renew car insurance before 30 Nov.

How it works

  1. The constructor with a Charset (Java 11) makes the encoding explicit.
  2. Try-with-resources closes and flushes the writer.

7. Using PrintWriter

PrintWriter adds println() and printf() for formatted output.

WriteWithPrintWriter.java
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);
    }
}
Output
Coffee    180.00
Sandwich  245.50

How it works

  1. %-8s left-aligns text and %7.2f right-aligns numbers with two decimals.
  2. Locale.ROOT keeps the decimal point as . on every computer.

8. Writing Binary Data

Binary data such as sensor readings or images is written as bytes.

WriteBytes.java
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);
    }
}
Output
Size after Files.write: 5
Size after FileOutputStream: 3

How it works

  1. Files.write(path, bytes) writes the whole array in one call.
  2. 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 FileWriter and PrintWriter.
  • 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() and Files.write() cover most simple cases in one line.
  • Use BufferedWriter for large or generated output.
  • Use PrintWriter for formatted text and FileWriter in classic code.
  • Write binary data with Files.write(path, bytes) or FileOutputStream.
  • Writing replaces content by default; use append mode to keep it.

Related Tutorials

11. Official Java Documentation References