Java – Write String to File
To write a String to a file in Java, you can use the built-in Files API, a writer such as FileWriter or PrintWriter, an output stream, or a library such as Apache Commons IO. For current Java versions, Files.writeString() is usually the simplest choice when the complete text is already available as a String.
This tutorial shows how to create or overwrite a text file, append text, write text line by line, choose a character encoding, and handle older Java versions. It also retains the stream-based and Apache Commons IO examples for cases where those APIs are already part of your code.
Write a String to a File with Files.writeString() in Java 11 and Later
Java 11 introduced Files.writeString(). With no open options, it creates the file if it does not exist and replaces the contents of an existing file. The overload shown below writes the text using UTF-8.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class WriteStringWithFiles {
public static void main(String[] args) {
Path path = Path.of("files/data1.txt");
String data = "Hello World!\nWelcome to www.tutorialkart.com";
try {
Files.writeString(path, data);
System.out.println("Data written to file successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
The parent directory must already exist. For example, if files does not exist, create it before calling Files.writeString().
Write the Java String with an Explicit UTF-8 Charset
Files.writeString(path, data) uses UTF-8 by default. You can still pass the charset explicitly when you want the encoding choice to be visible in the code.
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
Path path = Path.of("files/data1.txt");
String data = "Hello World!";
Files.writeString(path, data, StandardCharsets.UTF_8);
Write a String to a File in Java 8 with Files.write()
Files.writeString() is not available in Java 8. A compact Java 8 alternative is to convert the String to bytes with an explicit charset and pass those bytes to Files.write().
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class WriteStringJava8 {
public static void main(String[] args) {
Path path = Paths.get("files/data1.txt");
String data = "Hello World!\nWelcome to www.tutorialkart.com";
try {
Files.write(path, data.getBytes(StandardCharsets.UTF_8));
} catch (IOException e) {
e.printStackTrace();
}
}
}
As with Files.writeString(), the default behavior of Files.write() creates the target file if needed and truncates an existing file before writing.
Write a Java String Using BufferedOutputStream
BufferedOutputStream writes bytes rather than characters. This approach is useful when the surrounding code already works with byte streams. The String must first be converted to a byte array.
- Create a
Fileobject for the destination. - Create a
FileOutputStreamfor that file. - Wrap the file output stream in a
BufferedOutputStream. - Convert the String to a byte array.
- Call
BufferedOutputStream.write()with the byte array. - Use try-with-resources so the streams are closed even if writing fails.
WriteStringToFile.java
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* Java Example Program to Write String to File
*/
public class WriteStringToFile {
public static void main(String[] args) {
File file = new File("files/data1.txt");
String data = "Hello World!\nWelcome to www.tutorialkart.com";
try(FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos)) {
//convert string to byte array
byte[] bytes = data.getBytes();
//write byte array to file
bos.write(bytes);
bos.close();
fos.close();
System.out.print("Data written to file successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
FileOutputStream and BufferedOutputStream can throw IOException, so the example uses try-with-resources. The explicit close() calls inside this existing example are redundant because try-with-resources closes both streams automatically.
The example uses data.getBytes(), which relies on the JVM’s default charset. In new code, prefer an explicit charset such as data.getBytes(StandardCharsets.UTF_8) when the file encoding must be predictable across systems.
Run the program from the command prompt or from an IDE.
Output
Data written to file successfully.
Write a String to a File with FileWriter
FileWriter is a character-oriented API and is convenient when text is written in several calls. Current Java versions provide constructors that accept a Charset, so UTF-8 can be selected explicitly.
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class WriteStringWithFileWriter {
public static void main(String[] args) {
String data = "Hello World!\nWelcome to www.tutorialkart.com";
try (FileWriter writer =
new FileWriter("files/data1.txt", StandardCharsets.UTF_8)) {
writer.write(data);
} catch (IOException e) {
e.printStackTrace();
}
}
}
The FileWriter constructors that accept a Charset are available from Java 11. In Java 8, use Files.newBufferedWriter() with StandardCharsets.UTF_8 when you need explicit encoding.
Append a String to an Existing File in Java
Writing without append options replaces the current contents. To add text at the end of a file with Java 11 or later, pass StandardOpenOption.CREATE and StandardOpenOption.APPEND to Files.writeString().
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
Path path = Path.of("files/data1.txt");
String data = System.lineSeparator() + "This line is appended.";
Files.writeString(
path,
data,
StandardCharsets.UTF_8,
StandardOpenOption.CREATE,
StandardOpenOption.APPEND
);
CREATE allows the file to be created when it is missing, while APPEND places the new text after the existing content instead of truncating it.
Write a String to a File Line by Line
If the text is naturally represented as separate lines, Files.write() can write an iterable collection of lines. Java inserts the platform line separator after each item.
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;
Path path = Path.of("files/data1.txt");
List<String> lines = Arrays.asList(
"Hello World!",
"Welcome to www.tutorialkart.com"
);
Files.write(path, lines, StandardCharsets.UTF_8);
Write Multiple Text Lines with PrintWriter
PrintWriter is useful when text is produced one line at a time or when you want methods such as print(), println(), and printf(). The following example wraps a UTF-8 buffered writer.
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
Path path = Path.of("files/data1.txt");
try (PrintWriter writer = new PrintWriter(
Files.newBufferedWriter(path, StandardCharsets.UTF_8))) {
writer.println("Hello World!");
writer.println("Welcome to www.tutorialkart.com");
}
Create Parent Directories Before Writing the String
Java can create the target file, but Files.writeString() does not automatically create missing parent directories. Create the directory first when your path includes a folder that may not exist.
import java.nio.file.Files;
import java.nio.file.Path;
Path path = Path.of("files/data1.txt");
Files.createDirectories(path.getParent());
Files.writeString(path, "Hello World!");
Write a String to a File with Apache Commons IO
If your project already uses Apache Commons IO, FileUtils.writeStringToFile() provides another way to write text to a file.
- Create a file object with the path to the text file.
- Keep the text to write in a String.
- Call
FileUtils.writeStringToFile()with the file and text.
WriteStringToFile.java
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
/**
* Java Example Program to Write String to File
*/
public class WriteStringToFile {
public static void main(String[] args) {
File file = new File("files/data1.txt");
String data = "Hello World!\nWelcome to www.tutorialkart.com";
try {
//write string to file
FileUtils.writeStringToFile(file, data);
System.out.print("Data written to file successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Run this program, and you will get the following output.
Output
Data written to file successfully.
The two-argument FileUtils.writeStringToFile(File, String) overload used in the existing example is deprecated in current Apache Commons IO because it uses the default charset. For new code, pass a charset explicitly.
import java.io.File;
import java.nio.charset.StandardCharsets;
import org.apache.commons.io.FileUtils;
File file = new File("files/data1.txt");
String data = "Hello World!";
FileUtils.writeStringToFile(file, data, StandardCharsets.UTF_8);
Java String-to-File Methods: Which One Should You Use?
| Method | Best fit | Encoding |
|---|---|---|
Files.writeString() | Simple String-to-file writes on Java 11+ | UTF-8 by default; custom charset supported |
Files.write() | Java 8 compatibility, byte arrays, or collections of lines | Can be specified explicitly |
FileWriter | Writing character data in multiple calls | Charset constructor available from Java 11 |
PrintWriter | Line-oriented or formatted text | Depends on the wrapped writer |
BufferedOutputStream | Code that already works with byte streams | Determined when the String is converted to bytes |
FileUtils.writeStringToFile() | Projects that already depend on Apache Commons IO | Pass a Charset explicitly |
Important Details When Writing Java Strings to Files
- Overwrite versus append: the usual no-option
Files.writeString()call replaces existing content. UseAPPENDwhen the old content must remain. - Character encoding: use a known charset such as UTF-8 instead of relying on a platform default when files move between systems.
- Parent directories: create missing directories before writing the file.
- Resource handling: use try-with-resources for writers and streams so they are closed reliably.
- I/O errors: file permissions, invalid paths, missing directories, and storage errors can result in
IOException.
Java String-to-File Summary
For Java 11 and later, Files.writeString() is the most direct way to write a complete String to a text file. Java 8 code can use Files.write(), while FileWriter, PrintWriter, and buffered streams are useful when text is produced incrementally or the application already uses stream-based I/O. When Apache Commons IO is available, use the FileUtils.writeStringToFile() overload that accepts an explicit charset.
In this Java Tutorial, we learned how to write a String to a file using Java’s built-in file APIs, writers, streams, and Apache Commons IO.
TutorialKart.com