In this post, we will learn “How to read the content of file to a string in Java 11?”. Java 11 introduced readString() API to do that.

Here, we are going to learn following things:

  1. What is readString() API?
  2. How to use it?

Read content of a File to a String in Java 11 using readString methods?...!!! Click To Tweet

Let’s Begin,

1. What is readString() API?

Java 11 introduced two new overloaded methods as part of java.nio.file.Files class. 

readString​(Path path):

This 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 have been read or an I/O error, or other runtime exception, is thrown.

This method is equivalent to: readString(path, StandardCharsets.UTF_8)

readString1_Java11_Signature_Techndeck

readString​(Path path, Charset cs): 

Reads all characters from a file into a string, decoding from bytes to characters using the specified charset. The method ensures that the file is closed when all content have been read or an I/O error, or other runtime exception, is thrown.

This method reads all content including the line separators in the middle and/or at the end. The resulting string will contain line separators as they appear in the file.

readString2_Java11_Signature_Techndeck

2. How to use it?

Let’s take an example where we have a File (TestingFile.txt) which has some text written on that. Now, we are going to read that and write into a string using readString API.

Output:

Read content of a File to a String in Java 11 using readString methods?...!!! Click To Tweet

Do you like this Post? – then check my other helpful posts:

Other Useful References: