Selenium WebDriver Java Framework Course Limited Time Offer for $20

Selenium WebDriver Java Framework Course Limited Time Offer for $20

 

Print

Read File in Java

Using FileReader in java.io.File package, you can read a text file. See the example below. 

 

package com.seleniummaster.examplefile;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class ReadFileWithFileReader {

    public static void main(String[] args)
    {
   System.out.println(ReadToString("test.txt"));
    }

    public static String ReadToString(String FileToText)
    {
           String workingDir = System.getProperty("user.dir");
        StringBuilder fileContent=new StringBuilder();
        File filePath = new File(workingDir + File.separator);
        System.out.println(filePath);

        try
        {
            FileReader fr = new FileReader(filePath+File.separator+FileToText);
            BufferedReader br = new BufferedReader(fr);
            String sCurrentLine;
            while ((sCurrentLine = br.readLine()) != null) {
                fileContent.append(sCurrentLine);
            }

                   } catch (IOException e) {
            System.out.println("Cannot read the text file");
        }
        return fileContent.toString();
    }
}

Run the code and see the result below.

C:\seleniummaster
Hello TestSelenium MasterThis is a new test This is a new test