Files.writeString() / Files.write()
Methods for writing strings or byte arrays to a file (Java 11+). Using the utility methods of the Files class, you can write files without explicitly managing streams. Use StandardOpenOption.APPEND to append to an existing file.
Syntax
// Writes a string to a file (Java 11+).
Files.writeString(Path.of("file path"), string);
// Writes in append mode.
Files.writeString(Path.of("file path"), string, StandardOpenOption.APPEND);
// Writes a byte array or a list of strings.
Files.write(Path.of("file path"), list);
// Writes a byte array in append mode.
Files.write(Path.of("file path"), byteArray, StandardOpenOption.APPEND);
Method List
| Method / Option | Description |
|---|---|
| Files.writeString(Path, String) | Writes a string to a file (Java 11+). Overwrites the file by default. |
| Files.write(Path, List<String>) | Writes each element of a string list as a separate line. |
| Files.write(Path, byte[]) | Writes a byte array to a file. |
| StandardOpenOption.APPEND | Option to append to an existing file. |
| StandardOpenOption.CREATE | Option to create the file if it does not exist (included in the default behavior). |
Sample Code
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.Arrays;
import java.util.List;
// Writes a string to a file (overwrites).
try {
Files.writeString(Path.of("output.txt"), "Hello, Java!\n");
System.out.println("Write completed.");
} catch (IOException e) {
e.printStackTrace();
}
// Appends to the file.
try {
Files.writeString(
Path.of("output.txt"),
"Appended line\n",
StandardOpenOption.APPEND
);
} catch (IOException e) {
e.printStackTrace();
}
// Writes a list of strings (each element becomes one line).
List<String> lines = Arrays.asList("Line 1", "Line 2", "Line 3");
try {
Files.write(Path.of("lines.txt"), lines);
System.out.println("List write completed.");
} catch (IOException e) {
e.printStackTrace();
}
// Reads the file and checks its contents.
try {
String content = Files.readString(Path.of("lines.txt"));
System.out.println(content);
} catch (IOException e) {
e.printStackTrace();
}
Notes
By default, writeString() overwrites the file (CREATE, WRITE, TRUNCATE_EXISTING). To avoid accidentally overwriting an existing file, always specify StandardOpenOption.APPEND when appending.
The default character encoding is UTF-8. To write with a different encoding, pass a Charset as an argument (e.g., Files.writeString(path, str, StandardCharsets.UTF_8)).
For reading files, see Files.readString() / Files.readAllLines().
If you find any errors or copyright issues, please contact us.