Files Class readString() Method in Java with Examples
Last Updated :
27 Jan, 2023
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:
Input File
Below is the implementation of the problem statement:
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)
{
Path filePath
= Paths.get( "/home/mayur/" , "temp" , "gfg.txt" );
try
{
String content = Files.readString(filePath);
System.out.println(content);
}
catch (IOException e) {
e.printStackTrace();
}
}
}
|
Output:
Hello from GFG!
Share your thoughts in the comments
Please Login to comment...