Files readString() API

Learn to read a file to string in Java using Files.readString(path) method. This API has been introduced in Java 11.

1. Files.readString() Syntax

java.nio.file.Files class has two overloaded methods.

public static String readString​(Path path) throws IOException

public static String readString​(Path path, Charset cs) throws IOException
  • The first method reads all content from a file into a string, decoding from bytes to characters using the UTF-8 charset. The method ensures that the file is closed when all content has been read or an I/O error, or other runtime exception, is thrown.
  • The first method is equivalent to readString(path, StandardCharsets.UTF_8).
  • Second method does the same with with only using the specified charset.
  • Please note that these methods are not intended for reading very large files. Otherwise, they may throw OutOfMemoryError if the file is extremely large, e.g. larger than 2GB.

2. How to Read a File with readString()

Java program to read a file into string using Files.readString() method.

Path filePath = Path.of("c:/temp/demo.txt");

String content = Files.readString(filePath);

Drop me your questions in the comments section.

Happy Learning !!

Source Code on Github

Was this post helpful?

Join 8000+ Awesome Developers, Like YOU!

1 thought on “Files readString() API”

  1. Hey, I’m using readString on an xml file, but when I got to use a string method like .getLength() it just ignores it. I print to the console and it shows the string but the print of the length shows nothing


Leave a Comment

About HowToDoInJava

This blog provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.