Skip to content
Related Articles

Related Articles

Improve Article

Files Class readString() Method in Java with Examples

  • Last Updated : 05 Feb, 2021

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




// Implementation fo 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!

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :