微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

FileOutputStream

如何解决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初始化后添加该行。然后,您可以应用所需的逻辑来处理这种情况。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。