Selenium WebDriver Java Framework Course Limited Time Offer for $20

Selenium WebDriver Java Framework Course Limited Time Offer for $20

 

Print

Read Text File With Input Stream Reader Java

Using InputStreamReader in java.io.File package, you can read content of a text file. See the code example below. 

 

package com.seleniummaster.examplefile;

import java.io.*;

public class ReadTextFileWithInputStreamReader {

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

    public static String ReadToString(String FileToText) throws IOException {
        StringBuilder contents = new StringBuilder();
        String workingDir = System.getProperty("user.dir");
        File filePath = new File(workingDir + File.separator);
        System.out.println(filePath);
        Reader reader=null;
        try {
            InputStream inputStream = new FileInputStream(filePath + File.separator + FileToText);
            reader = new InputStreamReader(inputStream);

            int data = reader.read();
            while (data != -1) {
                char theChar = (char) data;
                data = reader.read();
                contents.append(theChar);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            reader.close();
        }
        return contents.toString();

    }
}

Run the code and see the result.

C:\seleniummaster
Hello Test
Selenium Master

Process finished with exit code 0