Open In App

Java Program to Read a File to String

Last Updated : 10 Oct, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

There are multiple ways of writing and reading a text file. This is required while dealing with many applications. There are several ways to read a plain text file in Java e.g. you can use FileReader, BufferedReader or Scanner to read a text file.

Given a text file, the task is to read the contents of a file present in a local directory and storing it in a string. Consider a file present on the system namely say it be ‘gfg.txt’. Let the random content in the file be as inserted below in the pretag block. Now we will be discussing out various ways to achieve the same. The content inside file ‘gfg.txt’ is as shown in the illustration block.

Illustration: Lines inside the file 

Geeks-for-Geeks
A computer science portal
World's largest technical hub

Note: Save above text file to your local computer with .txt extension and use that path in the programs. 

Methods:

There are several ways to achieve the goal and with the advancement of the version in java, specific methods are there laid out which are discussed sequentially.

Methods:

  1. Using File.readString() method
  2. Using readLine() method of BufferReader class
  3. Using File.readAllBytes() method
  4. Using File.lines() method
  5. Using Scanner class

Let us discuss each of them by implementing clean java programs in order to understand them.

Method 1: Using File.readString() method

The readString() method of File Class in Java is used to read contents to the specified file.

Syntax:

Files.readString(filePath) ;

Parameters: File path with data type as Path

Return Value: This method returns the content of the file in String format.

Note: File.readString() method was introduced in Java 11 and this method is used to read a file’s content into String.

Example

Java




// Java Program Illustrating Reading a File to a String
// Using  File.readString() method
 
// Importing required classes
import java.io.*;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
 
// Main class
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
        throws IOException
    {
 
        // Creating a path choosing file from local
        // directory by creating an object of Path class
        Path fileName
            = Path.of("C:\\Users\\HP\\Desktop\\gfg.txt");
 
        // Now calling Files.readString() method to
        // read the file
        String str = Files.readString(fileName);
 
        // Printing the string
        System.out.println(str);
    }
}


Output: 

Geeks-for-Geeks
A computer science portal
World's largest technical hub

Method 2: Using readLine() method of BufferReader class

BufferedReader is an object used to read text from a character-input stream. The readLine() method present in BufferReader method is used to read the file one line at a time and return the content.

Syntax: 

public String readLine() 
throws IOException

Parameters: This method does not accept any parameter.

Return value: This method returns the string that is read by this method and excludes any termination symbol available. If the buffered stream has ended and there is no line to be read then this method returns NULL.

Exceptions: This method throws IOException if an I/O error occurs.

Example 

Java




// Java Program Illustrating Reading a File to a String
// Using readLine() method of BufferReader class
 
// Importing required classes
import java.io.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
 
// MAin class
public class GFG {
 
    // Method 1
    // To read file content into the string
    // using BufferedReader and FileReader
    private static String method(String filePath)
    {
 
        // Declaring object of StringBuilder class
        StringBuilder builder = new StringBuilder();
 
        // try block to check for exceptions where
        // object of BufferedReader class us created
        // to read filepath
        try (BufferedReader buffer = new BufferedReader(
                 new FileReader(filePath))) {
 
            String str;
 
            // Condition check via buffer.readLine() method
            // holding true upto that the while loop runs
            while ((str = buffer.readLine()) != null) {
 
                builder.append(str).append("\n");
            }
        }
 
        // Catch block to handle the exceptions
        catch (IOException e) {
 
            // Print the line number here exception occurred
            // using printStackTrace() method
            e.printStackTrace();
        }
 
        // Returning a string
        return builder.toString();
    }
 
    // Method 2
    // Main driver method
    public static void main(String[] args)
    {
 
        // Custom input file path stored in string type
        String filePath = "C:\\Users\\HP\\Desktop\\gfg.txt";
 
        // Calling the Method 1 to
        // read file to a string
        System.out.println(method(filePath));
    }
}


Output: 

Geeks-for-Geeks
A computer science portal
World's largest technical hub

Method 3: Using File.readAllBytes() method

File.readAllBytes() method is used to read all the bytes from a file. The method ensures that the file is closed when all bytes have been read or an I/O error, or other runtime exception, is thrown. After reading all bytes, we pass those bytes to the string class constructor to create a string.

Syntax:  

public static byte[] ReadAllBytes (string path);

Parameter: Path which is the specified file to open for reading.

Approach: 

  • Declaring an empty string
  • get() method of Path class helps in fetching the file by passing as an argument to it.
  • Now readAllBytes() method of the File class is used to read the above file by passing into it.
  • Lastly, print the string.

Exceptions:

  • ArgumentException: The path is a zero-length string, contains only white space, or one or more invalid characters as defined by InvalidPathChars.
  • ArgumentNullException: The path is null.
  • PathTooLongException: The specified path, file name, or both exceed the system-defined maximum length.
  • DirectoryNotFoundException: The specified path is invalid.
  • IOException: An I/O error occurred while opening the file.
  • UnauthorizedAccessException: This operation is not supported on the current platform. OR the path specified a directory. OR the caller does not have the required permission.
  • FileNotFoundException: The file specified in the path was not found.
  • NotSupportedException: The path is in an invalid format.
  • SecurityException: The caller does not have the required permission.

Example 

Java




// Java Program Illustrating Reading a File to a String
// Using File.readAllBytes() method
 
// Importing required classes
import java.io.*;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
 
// Main class
public class GFG {
 
    // Method 1
    // To read the file content into string with
    // Files.readAllBytes(Path path)
    private static String method(String file_path)
    {
 
        // Declaring an empty string
        String str = "";
 
        // Try block to check for exceptions
        try {
 
            // Reading all bytes form file and
            // storing that in the string
            str = new String(
                Files.readAllBytes(Paths.get(file_path)));
        }
 
        // Catch block to handle the exceptions
        catch (IOException e) {
 
            // Print the exception along with line number
            // using printStackTrace() method
            e.printStackTrace();
        }
 
        return str;
    }
 
    // Method 2
    // Main driver method
    public static void main(String[] args)
    {
 
        // Path is passed from local directory of machine
        // and stored in a string
        String filePath = "C:\\Users\\HP\\Desktop\\gfg.txt";
 
        // Now call Method1 to
        // read the content in above directory
        System.out.println(method(filePath));
    }
}


Output: 

Geeks-for-Geeks
A computer science portal
World's largest technical hub

Method 4: Using File.lines() method

File.lines() method is used to read all lines from a file to stream. Then the bytes from the file are decoded into characters using the specified charset like UTF_8.

Syntax: 

public static Stream<String> lines(Path path, Charset cs)
throws IOException

Parameters: It generically takes two parameters: 

  • Charset to use for decoding.
  • Path of the file.

Return Type: The lines from the file as a string.

Example 

Java




// Java Program Illustrating Reading a File to a String
// Using File.lines() method
 
// Importing required classes
import java.io.*;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;
 
// Main class
public class GFG {
 
    // Method 1
    // To read the file content into the string with -
    // Files.lines()
    private static String method(String filePath)
    {
 
        // Declaring an object of StringBuilder class
        StringBuilder contentBuilder = new StringBuilder();
 
        // try block to check for exceptions
 
        // Reading file to string using File.lines() method
        // and storing it in an object of Stream class
        try (Stream<String> stream
             = Files.lines(Paths.get(filePath),
                           StandardCharsets.UTF_8)) {
            stream.forEach(
                s -> contentBuilder.append(s).append("\n"));
        }
 
        // Catch block to handle the exceptions
        catch (IOException e) {
 
            // Print the line number where exception occurred
            // using printStackTrace() method
            e.printStackTrace();
        }
 
        // Returning the string builder by
        // calling tostring() method
        return contentBuilder.toString();
    }
 
    // Method 2
    // Main driver method
    public static void main(String[] args)
    {
 
        // Custom file path is stored as string
        String filePath = "C:\\Users\\HP\\Desktop\\gfg.txt";
 
        // Calling method 1 to read content of a file
        System.out.println(method(filePath));
    }
}


Output: 

Geeks-for-Geeks
A computer science portal
World's largest technical hub

Method 5: Using next() and hasNext() method of Scanner class

Scanner class works by breaking the input into tokens that are sequentially retrieved from the input stream. Scanner class has two in build methods named next() and hasNext(). Both of these in-build methods return objects of type String. 

Example 

Java




// Java Program Illustrating Reading a File to a String
// Using next() and hasNext() method of Scanner class
 
// Importing required classes
import java.io.*;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Scanner;
 
// Main class
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
        throws IOException
    {
 
        // Creating object of Path class where custom local
        // directory path is passed as arguments using .of()
        // method
        Path fileName
            = Path.of("C:\\Users\\HP\\Desktop\\gfg.txt");
 
        // Creating an object of Scanner class
        Scanner sc = new Scanner(fileName);
 
        // It holds true till there is single element left
        // via hasNext() method
        while (sc.hasNext()) {
            // Iterating over elements in object
            System.out.println(sc.next());
        }
 
        // Closing scanner class object to avoid errors and
        //  free up memory space
        sc.close();
    }
}


Output:

Geeks-for-Geeks
A computer science portal
World's largest technical hub


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads