How to read and write text, Excel and CSV file in java?.

Write and Read Text txt file.

 import java.io.BufferedReader;  
 import java.io.BufferedWriter;  
 import java.io.File;  
 import java.io.FileNotFoundException;  
 import java.io.FileReader;  
 import java.io.FileWriter;  
 import java.io.IOException;  
 public class WriteandReadFile {  
   static File file;  
   public static void main(String[] a) throws FileNotFoundException, IOException {  
     try {  
       file = new File("writetextfile.txt");  
       // if file doesnt exists, then create it  
       if (!file.exists()) {  
         file.createNewFile();  
       }  
       // Write text on txt file.  
       FileWriter fw = new FileWriter(file, true);  
       BufferedWriter bw = new BufferedWriter(fw);  
       bw.write("How to write and read text file in java\n");  
       bw.close();  
     } catch (IOException e) {  
       e.printStackTrace();  
     }  
     // Read text from file.    
     FileReader fr = new FileReader(file);  
     BufferedReader br = new BufferedReader(fr);  
     String st;  
     while ((st = br.readLine()) != null) {  
       System.out.println(st);  
     }  
   }  
 }  

Write and Read data Excel file.

Download jxl.jar
 import java.io.File;  
 import java.io.IOException;  
 import jxl.Sheet;  
 import jxl.Workbook;  
 import jxl.read.biff.BiffException;  
 import jxl.write.Label;  
 import jxl.write.WritableSheet;  
 import jxl.write.WritableWorkbook;  
 import jxl.write.WriteException;  
 import jxl.write.Number;  
 public class ReadandWriteExcelFile {  
   public static void main(String[] args) throws BiffException, IOException, WriteException {  
     File file = new File("output.xls");  
     // if file doesnt exists, then create it  
     if (!file.exists()) {  
       file.createNewFile();  
     }  
     // Write Excel file using jxl api  
     WritableWorkbook wworkbook;  
     wworkbook = Workbook.createWorkbook(file);  
     WritableSheet wsheet = wworkbook.createSheet("First Sheet", 0);  
     for (int rows = 0; rows < 10; rows++) {  
       wsheet.addCell(new Label(0, rows, "First Coloum " + rows));  
       wsheet.addCell(new Number(1, rows, 3.1459 + rows));  
       wsheet.addCell(new Label(2, rows, "third Coloum " + rows));  
       wsheet.addCell(new Number(3, rows, 7895 + rows));  
     }  
     wworkbook.write();  
     wworkbook.close();  
     // Read Excel file using jxl api  
     Workbook workbook = Workbook.getWorkbook(file);  
     Sheet sh = workbook.getSheet(0);  
     for (int rows = 0; rows < sh.getRows(); rows++) {  
       for (int colm = 0; colm < sh.getColumns(); colm++) {  
    System.out.print(sh.getCell(colm, rows).getContents() + " ");  
       }  
       System.out.println();  
     }  
   }  
 }  


Write and Read data CSV file.

Download javacsv.jar
 import com.csvreader.CsvWriter;  
 import java.io.BufferedReader;  
 import java.io.File;  
 import java.io.FileNotFoundException;  
 import java.io.FileReader;  
 import java.io.FileWriter;  
 import java.io.IOException;  
 public class ReadandWriteCSVFile {  
   public static void main(String[] args) throws FileNotFoundException, IOException {  
     boolean alreadyExists = new File("Output.csv").exists();  
     try {  
  // use FileWriter constructor that specifies open for appending  
 CsvWriter csvOutput = new CsvWriter(new FileWriter("Output.csv",true),',');  
 // if the file didn't already exist then we need to write out the header line  
       if (!alreadyExists) {  
         csvOutput.write("Name");  
         csvOutput.write("Deparment");  
         csvOutput.write("Year");  
         csvOutput.endRecord();  
       }  
       // write out a few records  
       for (int i = 0; i < 10; i++) {  
         csvOutput.write("Studen " + i);  
         csvOutput.write("Deparment " + i);  
         csvOutput.write("201" + i);  
         csvOutput.endRecord();  
       }  
       csvOutput.close();  
     } catch (IOException e) {  
       e.printStackTrace();  
     }  
     // Read data from CSV file.    
     FileReader fr = new FileReader(new File("Output.csv"));  
     BufferedReader br = new BufferedReader(fr);  
     String st;  
     while ((st = br.readLine()) != null) {  
       System.out.println(st);  
     }  
   }  
 }  

How to find out broken links in Selenium Webdriver using java?.

More HTTP Status Code

 import java.io.IOException;  
 import java.net.HttpURLConnection;  
 import java.net.MalformedURLException;  
 import java.net.URL;  
 import java.util.List;  
 import java.util.concurrent.TimeUnit;  
 import org.openqa.selenium.*;  
 import org.openqa.selenium.firefox.FirefoxDriver;  
 public class Brokenlinks {  
   private static int statusCode;  
   public static void main(String[] args) throws IOException {  
     // Initialize web driver   
     WebDriver driver = new FirefoxDriver();  
     //Maximize browser window  
     driver.manage().window().maximize();  
     //Go to URL   
     driver.get("http://www.google.com");  
     //Set timeout   
   driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);  
 // Get all links web driver  
  List&lt;WebElement&gt; links = driver.findElements(By.tagName("a"));  
     for (int i = 0; i &lt; links.size(); i++) {  
 //remove null and empty links  
 if (!(links.get(i).getAttribute("href") == null) &amp;&amp; !(links.get(i).getAttribute("href").equals(""))) {  
  if (links.get(i).getAttribute("href").contains("http")) {  
  // Find HTTP Status-Code  
 statusCode= getResponseCode(links.get(i).getAttribute("href").trim());  
 // Check broken link  
 if (statusCode== 404) {  
 System.out.println("Broken of Link# "+i+" "+links.get(i).getAttribute("href"));  
           }  
         }  
       }  
     }  
     driver.close();  
   }  
 public static int getResponseCode(String urlString) throws MalformedURLException, IOException {      
     URL u = new URL(urlString);  
     HttpURLConnection huc = (HttpURLConnection) u.openConnection();  
     huc.setRequestMethod("GET");  
     huc.connect();  
     return huc.getResponseCode();  
  }  
 }  



How to handle javascript Popups in selenium webdriver using java?.

Please copy the below is the sample code for alerts, Confirmation Popups, Prompt Popups and make an html file.

<html>
<head>
<title>JavaScript Pupups </title>
</head>
<body>
<h2>Alert Box</h2>
<fieldset>
<legend>Alert Box</legend><p>Click the button to display an alert box.</p>
<button onclick="alertFunction()">Alerts</button>
<script>
function alertFunction()
{
alert("I am an example for alert box!");
}
</script>
</fieldset>

<h2>Confirm Box</h2>
<fieldset>
<legend>Confirm Box</legend>
<p>Click the button to display a confirm box.</p>
<button onclick="confirmFunction()">Confirm</button>
<p id="confirmdemo"></p>
<script>
function confirmFunction()
{
var cb;
var c=confirm("I am an Example for Confirm Box.\n Press any button!");
if (c==true)
  {
  cb="You Clicked on OK!";
  }
else
  {
  cb="You Clicked on Cancel!";
  }
document.getElementById("confirmdemo").innerHTML=cb;
}
</script>
</fieldset>

<h2>Prompt Box</h2>
<fieldset>
<legend>Prompt Box</legend>
<p>Click the button to demonstrate the prompt box.</p>
<button onclick="promptFunction()">Prompt</button>
<p id="promptdemo"></p>
<script>
function promptFunction()
{
var x;
var person=prompt("Please enter your name","Your name");
if (person!=null)
  {
  x="Hello " + person + "! Welcome to Selenium Easy..";
  document.getElementById("promptdemo").innerHTML=x;
  }
}
</script>
</fieldset>
</body>
</html>


Handle JavaScript Popups in selenium webdriver using java

 import org.openqa.selenium.Alert;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.firefox.FirefoxDriver;  
 public class JavaScriptPopup {  
   public static void main(String[] a) throws InterruptedException {  
     // Initialize Web driver   
     WebDriver driver = new FirefoxDriver();  
     //Maximize browser window   
     driver.manage().window().maximize();  
     //Go to Page   
     driver.get("file:///E:/Javascript%20Popup.html");  
      //===========Alerts ======    
     //click on button  
     driver.findElement(By.xpath("html/body/fieldset[1]/button")).click();  
     //handle to the open alert.  
     Alert alert = driver.switchTo().alert();  
     //get the text which is present on th Alert.  
     System.out.println(alert.getText());  
     Thread.sleep(3000);  
     //Click on OK button.  
     alert.accept();  
     //===========Confirmation Popups======    
     //click on button  
     driver.findElement(By.xpath("html/body/fieldset[2]/button")).click();  
     //handle to the open confirmation popup.  
     Alert Confirm = driver.switchTo().alert();  
     Thread.sleep(3000);  
     //click on Cancel button.  
     Confirm.dismiss();  
     //===========Prompt Popups======  
     //click on button  
     driver.findElement(By.xpath("html/body/fieldset[3]/button")).click();  
     //handle to the open prompt popup.  
     Alert Prompt = driver.switchTo().alert();  
     //pass the text to the prompt popup  
     Prompt.sendKeys("Prompt Box");  
     Thread.sleep(3000);  
     //Click on OK button.  
     Prompt.accept();  
     //close browser  
     driver.quit();  
   }  
 }  

How to run Chrome, IE, Safari, Opera and Mozilla Firefox on selenium webdriver using java?.


Mozilla Firefox
Download WebDriver jar files for Mozilla Firefox. Add all jar files in your project


 import java.util.concurrent.TimeUnit;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.firefox.FirefoxDriver;  
 public class MozillaFirefoxbrowser {  
   public static void main(String args[]) {  
     // Initialize driver    
     WebDriver dr = new FirefoxDriver();  
     //Maximize browser window     
     dr.manage().window().maximize();  
     //Go to URL    
     dr.get("http://www.google.com");  
     //Set timeout    
     dr.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);  
     //close firefox browser  
     dr.close();  
   }  
 }  

Internet Explorer
Download Internet Explorer Driver Server

 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.ie.InternetExplorerDriver;  
 public class InternetExplorerBrowser {  
   public static void main(String args[]) {  
     //set the system property for Internet Explorer  
  //System.setProperty("webdriver.ie.driver", "Location of IE Driver");  
  System.setProperty("webdriver.ie.driver", "IEDriverServer.exe");  
     // Initialize IE driver   
     WebDriver driver = new InternetExplorerDriver();  
     //Maximize browser window     
     driver.manage().window().maximize();  
     //Go to URL    
     driver.get("http://www.google.com"); 
     //close Internet Explorerbrowser  
     driver.quit();  
   }  
 }  
 <center>  

Google Chrome
Download Chrome Driver Server

 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.chrome.ChromeDriver;  
 import org.openqa.selenium.ie.InternetExplorerDriver;  
 public class Chromebrowser {  
   public static void main(String args[]) {  
     //set the system property for Chrome  
 //System.setProperty("webdriver.chrome.driver", "Location of Chrome Driver");  
   System.setProperty("webdriver.chrome.driver", "chromedriver.exe");  
     // Initialize IE driver   
     WebDriver driver = new ChromeDriver();  
     //Maximize browser window     
     driver.manage().window().maximize();  
     //Go to URL    
     driver.get("http://www.google.com");  
   }  
 }  

Safari
Download Selenium WebDriver for Safari. Add jar file in your project

 import java.util.concurrent.TimeUnit;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.firefox.FirefoxDriver;  
 public class Safaribrowser {  
   public static void main(String args[]) {  
     // Initialize driver    
     WebDriver dr = new SafariDriver();  
     //Maximize browser window     
     dr.manage().window().maximize();  
     //Go to URL    
     dr.get("http://www.google.com");  
     //Set timeout    
     dr.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);  
     //close Safari browser  
     dr.quit();  
   }  
 }  



Opera
Download Selenium WebDriver for Opera. Add jar file in your project
 import com.opera.core.systems.OperaDriver;  
 import java.util.concurrent.TimeUnit;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.remote.DesiredCapabilities;  
 public class Operabrowser {  
   public static void main(String args[]) { 
 
        //System.setProperty("webdriver.ie.driver", "Location of opera Driver");
        System.setProperty("webdriver.ie.driver", "operadriver.exe");
        // Initialize Opera driver
       WebDriver  driver = new OperaDriver();
 
     //Maximize browser window     
     driver .manage().window().maximize();  
     //Go to URL    
     dr.get("http://google.com");  
     //Set timeout    
     driver .manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);  
     //close Oper browser  
     driver .quit();  
   }  
 }  

HtmlUnit Driver

 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.htmlunit.HtmlUnitDriver;  
 public class Htmlunit {  
   public static void main(String args[]) {  
     // Initialize driver     
     WebDriver dr = new HtmlUnitDriver();  
     //Go to page     
     dr.get("http://www.google.com");  
     //get page title     
     System.out.println("Title =: " + dr.getTitle());  
     //get page url  
     System.out.println("URL =: " + dr.getCurrentUrl());  
     //close Htmlunit   
     dr.close();  
   }  
 }  


How to open and close tab in selenium webdriver using java?.

 import java.util.concurrent.TimeUnit;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.Keys;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.firefox.FirefoxDriver;  
 public class OpenandClosenewtab {  
   public static void main(String[] a) throws InterruptedException {  
     // Initialize driver   
     WebDriver dr = new FirefoxDriver();  
     //Maximize browser window    
     dr.manage().window().maximize();  
     //Go to URL   
     dr.get("http://www.google.com");  
     //Set timeout   
 dr.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);  
     // Open new tab   
 dr.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "t");  
     //Go to URL   
     dr.get("http://www.gmail.com");  
     //Set new tab timeout   
 dr.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);  
     // Do some operation       
     dr.findElement(By.id("gmail-sign-in")).click();  
     dr.findElement(By.id("Email")).sendKeys("WebDriver");  
     dr.findElement(By.id("Passwd")).sendKeys("WebDriver");  
     dr.findElement(By.id("signIn")).click();  
     Thread.sleep(2000);  
     // Close new tab   
 dr.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "w");  
     // Switch first tab   
     dr.switchTo().defaultContent();  
     Thread.sleep(2000);  
     // Write search String   
     dr.findElement(By.id("gbqfq")).sendKeys("WebDriver");  
     // Click on Search button       
     dr.findElement(By.id("gbqfb")).click();  
     Thread.sleep(2000);  
     // Browser close    
     dr.close();  
   }  
 }  

How can switch between browser tabs in selenium webdriver using java?.

 import java.util.concurrent.TimeUnit;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.Keys;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.firefox.FirefoxDriver;  
 public class Switchbetweenbrowsertab {  
   public static void main(String[] a) throws InterruptedException {  
     // Initialize driver  
     WebDriver driver = new FirefoxDriver();  
     //Maximize browser window   
     driver.manage().window().maximize();  
     //Go to URL  
     driver.get("http://www.google.com");  
     //Set timeout  
 driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);  
     // Open new tab  
 driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "t");  
     //Go to URL  
     driver.get("http://www.gmail.com");  
     //Set new tab timeout  
  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);  
     // Do some operation      
     driver.findElement(By.id("gmail-sign-in")).click();  
     driver.findElement(By.id("Email")).sendKeys("WebDriver");  
     driver.findElement(By.id("Passwd")).sendKeys("WebDriver");  
     driver.findElement(By.id("signIn")).click();  
     Thread.sleep(2000);  
     // Switch first tab  
 driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "\t");  
     driver.switchTo().defaultContent();  
     Thread.sleep(2000);  
     // Write search String  
     driver.findElement(By.id("gbqfq")).sendKeys("WebDriver");  
     // Click on Search button      
     driver.findElement(By.id("gbqfb")).click();  
     Thread.sleep(2000);  
     // Browser close   
     driver.close();  
   }  
 }  

How to check if an element exists in WebDriver selenium with java?.

 import java.util.concurrent.TimeUnit;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.firefox.FirefoxDriver;  
 public class Elementexists {  
 public static void main(String[] a) throws InterruptedException {  
     // Initialize driver  
     WebDriver driver = new FirefoxDriver();  
     //Maximize browser window   
     driver.manage().window().maximize();  
     //Go to URL  
     driver.get("http://www.google.com");  
     //Set selenium webdriver get timeout  
 driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);  
     // Write search String  
 driver.findElement(By.id("gbqfq")).sendKeys("WebDriver");  
     // Check element exists  
  if (driver.findElements(By.id("gbqfb")).size() != 0) {  
       driver.findElement(By.id("gbqfb")).click();  
       System.out.println("element exists");    
     }  
     Thread.sleep(5000);  
     // Browser close   
     driver.close();  
   }  
 }  

How to handle browser authentication in Selenium Webdriver using Java?.


 import java.util.concurrent.TimeUnit;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.firefox.FirefoxDriver;  
  public class AuthinticationRequired {   
   public static void main(String[] a) {   
   // Initialize driver   
    WebDriver driver = new FirefoxDriver();   
   //Maximize browser window    
   driver.manage().window().maximize();   
  //driver.get("http://Username:Password@domain_name");   
     //Go to URL   
    driver.get("http://dipil:bangla@localhost:4040");   
  //Set selenium webdriver get timeout   
  driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);     
    // Browser close    
    driver.close();   
   }   
  }