Monday 9 October 2017

Reading a file as String

Sometimes we need to read test input from a file(.txt/.xml etc) and enter into a text area field. Below code will help to read the content of file and stored in a string.

To achieve this we need to take the help of Apache CommonsIO. This will be available at Apache CommonsIO and download  zip file

Extract the zip file and you will find commons-io-2.5.jar file

Add the jar file to the project 

import java.io.File;
import java.nio.charset.Charset;
import org.apache.commons.io.FileUtils;

public class ReadFileToString {
public static void main(String[] args){
File inputFile = new File("d://test.xml");
//location of the tile
try {
               //Reading file to string
String str = FileUtils.readFileToString(inputFile,Charset.forName("utf-8"));
   System.out.println(str);
} catch (Exception e) {
    e.printStackTrace();
}
}
}

With the help of above code, we can have the content of file. Now we can use the variable to enter the text in text area input field.

In this case, 

driver.findElement(By.id("TextArea")).sendKeys(str);

No comments:

Post a Comment