Java MCQ: What does the Files.readString() method in Java 11 return?
Answer:
Explanation:
The Files.readString()
method, introduced in Java 11, reads the content of a file and returns it as a single string. This method simplifies reading text files by providing a straightforward way to obtain the entire content of a file as a string, without the need to manually handle streams or readers.
Here’s an example of using Files.readString()
:
import java.nio.file.Files;
import java.nio.file.Path;
public class FilesReadStringExample {
public static void main(String[] args) throws Exception {
Path filePath = Path.of("example.txt");
String content = Files.readString(filePath);
System.out.println(content);
}
}
In this example, Files.readString(filePath)
reads the content of the file example.txt
and returns it as a single string, which is then printed to the console.
The Files.readString()
method is particularly useful when you need to quickly read the content of a text file into memory for processing or display.
Reference links:
https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html