Files.writeString()
Writes a string to a file, creating or overwriting it.
Available since: Java 11
Syntax
static Path writeString(Path path, CharSequence csq, OpenOption... options) throws IOExceptionParameters
| Parameter | Type | Description |
|---|---|---|
| path | Path | The path to the file. The folder must exist. |
| csq | CharSequence | The text to write. |
| options | OpenOption... | The mode: for example, StandardOpenOption.APPEND to add to the end. |
Return value
PathThe same path.
Examples
Overwriting and appending:
void main() throws IOException {
Path log = Path.of("log.txt");
Files.writeString(log, "start\n");
Files.writeString(log, "step 1\n", StandardOpenOption.APPEND);
Files.writeString(log, "step 2\n", StandardOpenOption.APPEND);
IO.print(Files.readString(log));
Files.delete(log);
}Output:
start
step 1
step 2Writing a list of lines — Files.write():
void main() throws IOException {
Path file = Path.of("names.txt");
Files.write(file, List.of("Anna", "Oleg", "Maria"));
IO.println(Files.readAllLines(file));
Files.delete(file);
}Output:
[Anna, Oleg, Maria]Notes
Without options the file is created, and if it exists its contents are fully replaced. If the folder does not exist you get NoSuchFileException — create it with Files.createDirectories(). The default encoding is UTF-8.
See also
- Files.readString() — Reads a whole text file into one string.
- Files.exists() — Checks whether a file or folder exists. Related: isDirectory(), isRegularFile(), size().
- Files.createDirectories() — Creates a folder together with all missing parent folders.
- Files.delete() — Deletes a file or an empty folder. deleteIfExists() does not throw if the file is missing.
Related recipes
In the tutorial
- Reading and writing files — Reading and writing text files in Java — Files.writeString, readString, readAllLines, write, appending to the end, Files.lines and buffered streams.