如何在java中动态提供属性文件名

时间:2015-09-21 09:16:10

标签: java

您好我正在使用两个属性文件。一个用于应用程序配置,另一个用于对象存储库。我将在我的应用程序中使用这两个属性。对于每个测试用例,我正在初始化属性并使用属性对象访问文件。但我想在单独的类中的单独方法中初始化属性。我也想在另一个类中调用该方法并使用该初始化的属性对象访问属性文件。我不知道该怎么做。请帮我完成这项任务。谢谢提前

以下是我的代码

public class PropertiesExample {

    public static void main(String[] args) {

        WebDriver driver = null;
        String baseUrl;
        File file = new File("/home/vaav/workspace/PropertiesExample/config.properties");
        Properties prop = new Properties();
        FileInputStream fileIO = null;

        try{
            fileIO = new FileInputStream(file);
            prop.load(fileIO);
            fileIO.close();
        }catch(FileNotFoundException ex){
            ex.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.setProperty("webdriver.chrome.driver", "/home/vaav/workspace/PropertiesExample/lib/chromedriver");
        driver = new ChromeDriver();
        baseUrl = prop.getProperty("URL");
        driver.get(baseUrl+"/");

        driver.manage().window().maximize();
        driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

        driver.findElement(By.xpath(prop.getProperty("Login.btnAdmin"))).click();
        driver.findElement(By.id(prop.getProperty("Login.txtUsername"))).sendKeys(prop.getProperty("userName"));
        driver.findElement(By.id(prop.getProperty("Login.txtPassword"))).sendKeys(prop.getProperty("password"));
        driver.findElement(By.id(prop.getProperty("Login.btnSignIn"))).click();
    }

}

我想在另一个文件中执行与属性相关的内容并使该代码可重用

2 个答案:

答案 0 :(得分:0)

选择属性文件的默认文件名和位置。例如。 “./config.properties”假设属性文件在启动时在user.dir中。或者通过资源加载器从类路径加载相同的文件,例如

    final InputStream stream =
       this.getClass().getResourceAsStream("config.properties");
properties.load(stream);

但是也可以选择通过系统属性覆盖默认位置。系统。

 String configLocation = System.getProperties().getProperty("properties.location");

如果configLocation不为null,请使用用户指定的位置。否则使用默认值。

答案 1 :(得分:0)

您可以允许用户通过命令行参数指定它:

String configLocation == "default/location/config.properties"
if(args.length >= 1){
    configLocation = args[0];
    //You could also test here that the file exists
}