The readString() method of File Class in Java is used to read contents to the specified file.
Syntax:
Files.readString(filePath)
Parameters:
path - File path with data type as Path
Return Value: This method returns the content of the file in String format.
Below are two overloaded forms of the readString() method.
public static String readString(Path path) throws IOException public static String readString(Path path, Charset cs) throws IOException
- Using the UTF-8 charset in the first method reads all content from a file into a string, decoding from bytes to characters.
- The second method does the same using the specified charset.
Input File:
Below is the implementation of the problem statement:
Java
// Implementation for readString() method in Java import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class GFG { public static void main(String[] args) { // creating path Path filePath = Paths.get( "/home/mayur/" , "temp" , "gfg.txt" ); try { // reading file from given path String content = Files.readString(filePath); // printing the content System.out.println(content); } catch (IOException e) { e.printStackTrace(); } } } |
Output:
Hello from GFG!