[读取硒中的属性文件时发生NullPointerException

问题描述 投票:0回答:3

我有下面的代码:

public class BasePage {
    public static WebDriver driver;
    public static Properties prop;
    FileInputStream objfile;

    @Test
    public void BasePages() throws IOException {
        try {
            prop = new Properties();

            objfile = new FileInputStream(System.getProperty("app.properties"));
            prop.load(objfile);
            System.out.println("file loaded");
        } catch (Exception e) {
            System.out.println("catch exception" + e);
        }
    }
}

FileInputStream显示NullPointerException。仅在读取此行将其移到catch块后,我才尝试调试上述代码。

任何人都可以解释为什么我会收到异常以及如何解决此问题吗?

app.properties文件包含以下几行:

baseUrl = "https://www.google.com/";
browser="chrome";
java selenium-webdriver automated-tests properties-file fileinputstream
3个回答
0
投票

请尝试以下解决方案:

   try {

    InputStream  objfile = new FileInputStream("path/to/app.properties")) {

    Properties prop = new Properties();

    // load a properties file
    prop.load(input);

    // get the property value and print it out
    System.out.println(prop.getProperty("baseUrl"));
    System.out.println(prop.getProperty("browser"));


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

0
投票
objfile= new FileInputStream(System.getProperty("app.properties"));

上面的行引起了此问题,因为System.getProperty("app.properties")返回null。不知道为什么要使用它。

仅删除System.getProperty(),如下所示。确保使用正确的文件路径

objfile = new FileInputStream("app.properties");

如果您打算访问当前项目目录,则代码应该是

objfile = new FileInputStream(System.getProperty("user.dir")+"/"+"app.properties");

0
投票
  1. 给出完整属性文件路径objfile = new FileInputStream(“提供完整属性文件路径”)

  2. 如果由于错误的路径而未创建作为对象的'objfile'

  3. 并且我们试图取消引用一个空对象,因此得到空指针异常prop.load(objfile);

注意-我给出的答案最快,可以在评论部分看到。请在接受的同时考虑,谢谢

© www.soinside.com 2019 - 2024. All rights reserved.