FileOutputStream

问题描述

我试图从互联网上获取一些数据,然后将其保存在txt文件中,但是却收到了一个N​​ullpointer异常,内容为: INFO:检测到的方言:W3C mypackage.testClass.main(testClass.java:31)处的线程“ main”中的异常java.lang.NullPointerException。 因此,它实际上将我引向了这一行: byte [] contentInBytes = aaa.getBytes();

代码如下:

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();
        }
        
        
    }

}

解决方法

这不是特定的解决方案,而是用于找到答案的建议。

为了弄清楚何时以及为什么收到该NullPointerException,可以临时打印aaa

System.out.println("i = " + i + " -> aaa = " + aaa);

aaa初始化后添加该行。然后,您可以应用所需的逻辑来处理这种情况。