Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Files.readString()

Reads a whole text file into one string.

Available since: Java 11

Syntax

static String readString(Path path) throws IOException

Parameters

ParameterTypeDescription
pathPathThe path to the file. The default encoding is UTF-8; another one can be passed as the second argument.

Return value

StringThe file contents.

Examples

Writing a file and reading it back whole:

void main() throws IOException {
    Path file = Path.of("note.txt");
    Files.writeString(file, "Buy milk\nCall Anna\n");
 
    String text = Files.readString(file);
    IO.print(text);
    IO.println(text.length());
    Files.delete(file);
}

Output:

Buy milk
Call Anna
19

A missing file throws NoSuchFileException:

void main() {
    try {
        Files.readString(Path.of("missing.txt"));
    } catch (IOException e) {
        IO.println(e.getClass().getSimpleName() + ": " + e.getMessage());
    }
}

Output:

NoSuchFileException: missing.txt

Notes

The method throws the checked IOException, so you must catch it or declare throws IOException. It suits small files: the whole contents end up in memory. Read large files line by line with Files.lines() or BufferedReader.

See also

  • Files.writeString() — Writes a string to a file, creating or overwriting it.
  • Files.readAllLines() — Reads a text file into a list of lines.
  • Files.lines() — Reads a file lazily as a stream of lines, without loading it into memory.
  • Path.of() — Creates a Path object — a path to a file or folder.
  • IOException — A checked exception for input and output errors: files, network, data streams.

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.

Thanks for reading!

Donate to the site — we work hard for you.