Java/selenium Nullpointer exception for FileOutputStream

I am trying to get some data from the internet and then save it in a txt file but i am getting a Nullpointer Exception which reads: INFO: Detected dialect: W3C Exception in thread “main” java.lang.NullPointerException at mypackage.testClass.main(testClass.java:31). So, its actually directing me to this line: byte[] contentInBytes = aaa.getBytes();

Here is the code:

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.*;



public class testClass {

    public static void main(String[] args) {
        System.setProperty("webdriver.gecko.driver","chromedriver");
        WebDriver driver = new ChromeDriver();
        driver.get("https://www.blablawebsite.com/path");
        List<WebElement> urls = driver.findElements(By.xpath("//li[contains(@text(),'text')]"));
        int i;
        
        try {
            File file = new File("/path/to/file/text.txt");
            FileOutputStream fos = new FileOutputStream(file); 
            if(!file.exists()) 
                file.createNewFile();
            
                for(i=0; i <urls.size(); i++) { 
                    String aaa = urls.get(i).getAttribute("data-asin");
                    byte[] contentInBytes = aaa.getBytes();
                    fos.write(contentInBytes);
                    fos.flush();
                    fos.close();
            
            }
                
                
            
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        
        
    }

}
1 Like

It seems that data which you’re downloading from internet doesn’t have data-asin attribute available. So while finding the attribute value, you’re getting NULL value.

When you perform any operation on a NULL value i.e aaa.getBytes() you get NullPointerException

1 Like