Automation Using Selenium Webdriver

Tuesday, 1 November 2016

Read-Write Text File In Java - Tutorials For WebDriver

We have learnt about String class and Its different functions In my previous post.
Now our next topic Is How to write In to text file or How to read text file In java software
development language. Many times you will need reading or writing text file In your selenium webdriver
software automation test case development. For Example, You are reading some large data from
web page of software web application and wants to store It In text file to use It somewhere else In
future. Same way, You have to read data from file for some purpose.

It Is very easy to Create, Write and read text file In java software development language.
We can use java built in class File to create new file, FileWriter and BufferedWriter class to write
In to file, FileReader and BufferedReader class to read text file.

Bellow given example will first of all create temp.txt file In D: drive and then write two line In to
It. Then It will read both lines one by one from text file using while loop and print In console.
You can use bellow given example code of software development language for reading or writing text
 file In your selenium webdriver software automation test case whenever needed.

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

public class RW_File {

 public static void main(String[] args) throws IOException {
  //Create File In D: Driver.
  String TestFile = "D:\\temp.txt";
  File FC = new File(TestFile);//Created object of java File class.
  FC.createNewFile();//Create file.

  //Writing In to file.
  //Create Object of java FileWriter and BufferedWriter class.
  FileWriter FW = new FileWriter(TestFile);
  BufferedWriter BW = new BufferedWriter(FW);
  BW.write("This Is First Line."); //Writing In To File.
  BW.newLine();//To write next string on new line.
  BW.write("This Is Second Line."); //Writing In To File.
  BW.close();

  //Reading from file.
  //Create Object of java FileReader and BufferedReader class.
  FileReader FR = new FileReader(TestFile);
  BufferedReader BR = new BufferedReader(FR);
  String Content = "";

  //Loop to read all lines one by one from file and print It.
  while((Content = BR.readLine())!= null){
   System.out.println(Content);
  }
 }
}

1 comment:

  1. Hello Reddy,

    Thanks for sharing read and write the data from text. I would like to know how to read and write the data from .xlsx file. Here i am facing big issue is , How to get the cell and row values ? Please reply me asap.

    Thanks in advance.

    Regards,

    Subhani
    +91- 80196 47951

    ReplyDelete