Java
Programming
File Manipulation
String Handling
Coding Tips

How do I save a String to a text file using Java?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Saving a String to a text file in Java is simple, but the best API depends on what you need. For modern Java, Files.writeString() is the clearest choice. Older APIs such as FileWriter and BufferedWriter still matter when you want compatibility or more control.

The main decisions are whether you want to overwrite or append, which character encoding you need, and how you want to handle I/O errors. Once those are clear, the code is short.

Use Files.writeString() in Modern Java

If you are on Java 11 or newer, Files.writeString() is the cleanest option.

java
1import java.io.IOException;
2import java.nio.charset.StandardCharsets;
3import java.nio.file.Files;
4import java.nio.file.Path;
5
6public class SaveStringExample {
7    public static void main(String[] args) throws IOException {
8        String text = "Hello from Java";
9        Path path = Path.of("example.txt");
10
11        Files.writeString(path, text, StandardCharsets.UTF_8);
12    }
13}

This overwrites the file if it exists. It also makes the character encoding explicit, which is a good habit whenever text leaves memory and goes to disk.

Append Instead of Overwriting When Needed

If you want to keep the existing file contents and add more text, include append options:

java
1import java.io.IOException;
2import java.nio.charset.StandardCharsets;
3import java.nio.file.Files;
4import java.nio.file.Path;
5import java.nio.file.StandardOpenOption;
6
7public class AppendStringExample {
8    public static void main(String[] args) throws IOException {
9        Path path = Path.of("example.txt");
10
11        Files.writeString(
12            path,
13            "Another line\n",
14            StandardCharsets.UTF_8,
15            StandardOpenOption.CREATE,
16            StandardOpenOption.APPEND
17        );
18    }
19}

CREATE ensures the file is made if it does not exist yet. APPEND changes the write mode from overwrite to add-at-end.

Use BufferedWriter or FileWriter for Older Style Code

If you want a classic streaming API or need compatibility with older Java codebases, BufferedWriter remains a solid option.

java
1import java.io.BufferedWriter;
2import java.io.FileWriter;
3import java.io.IOException;
4
5public class BufferedWriterExample {
6    public static void main(String[] args) {
7        try (BufferedWriter writer = new BufferedWriter(new FileWriter("example.txt"))) {
8            writer.write("Hello from BufferedWriter");
9            writer.newLine();
10            writer.write("Second line");
11        } catch (IOException e) {
12            e.printStackTrace();
13        }
14    }
15}

This style is useful when you are writing incrementally or when the code already works with writers and streams.

Handle Encoding and Errors Deliberately

The main hidden issue in file writing is not the write call itself. It is the assumptions around encoding and failure handling.

Good defaults are:

  • use UTF-8 explicitly
  • use try-with-resources when working with writers
  • decide whether the program should throw or recover from IOException

For utility scripts, throwing the exception may be fine. For servers or desktop apps, logging and user-facing error handling are usually better.

It is also worth thinking about line endings. If the text should appear on separate lines, add \n explicitly or use newLine() when working with a buffered writer.

Common Pitfalls

The biggest mistake is relying on the platform default encoding without realizing it. A file written on one machine can look wrong on another if the encoding is implicit.

Another common issue is forgetting that Files.writeString() overwrites by default. If you expected append behavior, you need explicit open options.

It is also easy to skip try-with-resources when using writer-based APIs. That can leave file handles open longer than intended.

Finally, do not swallow IOException silently. File writes fail for real reasons such as missing permissions, missing directories, or full disks, and those failures should surface clearly.

Summary

  • Use Files.writeString() for the simplest modern Java solution.
  • Specify UTF-8 explicitly when writing text files.
  • Use append options when you want to keep existing content.
  • Use BufferedWriter or FileWriter when a stream-style API fits better.
  • Handle IOException intentionally instead of ignoring it.

Course illustration
Course illustration

All Rights Reserved.