Create a screenshot in Selenium

Upcasting : Casting from a subclass to a superclass is called upcasting , Happens implicitly or automatically.

No methods specific to subclass will be available

So, upcasting narrows the number of available methods

Downcasting: Superclass to sub class, widening , happens explicitly

So, Downcasting widens the number of available methods

Syntax: Cat cat = new Cat();

Animal animal = cat;

animal = (Animal) cat;

Note: The FIles package used is

import com.google.common.io.FileWriteMode;
import com.google.common.io.Files;

Take Screenshot using FIle:

// Take the screenshot using TakesScreenshot

File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

//Create a file object for destination directory

File folder= new File("D:/new/screenshots/test/");  

//make the directory 
folder.mkdirs();

//create a file object for destination
File des=new File("D:/new/screenshots/test/ne1w.png");

//create a file object for source , here getabsolutepath gives the temporary storage path.

File src= new File(scrFile.getAbsolutePath());
        
   
// move the file from src to new destination  

try {
	Files.move(src, des);
} catch (IOException e) {
e.printStackTrace();
		}

Using FIles:

// Take screenshot: This will be stored in tmp location

File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        
//Get tmp location path
        File src= new File(scrFile.getAbsolutePath());
      
//create a destination file path
        File des= new File("D:/new/newscreenshots/test/n2ew.png");
        
        try {
//create parent directories and move src to destination
			Files.createParentDirs(des);
			Files.move(src, des);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

Using FileOutputStream:

//create destination Path

File tmp1=new File("D:/new/newscreenshots/test/test/praveen.png");   
        
        
		try {
//create destination parent directories
			Files.createParentDirs(tmp1);

//create an output stream
			FileOutputStream a = new FileOutputStream(tmp1);

//write the screenshot bytes to the output stream			a.write(((TakesScreenshot)driver).getScreenshotAs(OutputType.BYTES));
		} catch (Exception e3) {
			// TODO Auto-generated catch block
			e3.printStackTrace();
		}

How to write to a file:

String a= "Write this to File";
byte[] b=a.getBytes();
File tmp=new File("D:/new/newscreenshots/test/n2ew.txt");
        

try {

// if parent directory doesn't exists, even if it exists it won't overwrite

Files.createParentDirs(tmp);
Files.write(b, tmp);

} catch (IOException e1) {
	e1.printStackTrace();
}
        

Best solution:

File tmp1= new  File("D:/test.txt");		
	
try{

FileOutputStream a = new FileOutputStream(tmp1);
a.write("hitwewe".getBytes());
a.write("checkmate".getBytes());

}catch (Exception e){

e.printStackTrace();

}