如何从其他类读取conf.properties文件?

时间:2014-10-01 16:45:48

标签: java

我是Selenium的初学者,我创建了一个名为ReadPropertyFile的阅读类名。在本课程中,我编写了一个用于阅读config.properties文件的代码。现在我有一个主要课程,我想从中调用ReadPropertyFile类及其活动,我可以从中读取config.properties文件。

请帮我解决下面的代码:

ReadPropertyFile.java:

public class ReadPropertyFile {

    public static void main(String[] arg)throws IOException{

        // Read configuration properties file

        String projdir = System.getProperty("user.dir");
        String propfilepath = projdir+"\\configuration\\"+"conf.properties";
        Properties p = new Properties();
        p.load(new FileInputStream(propfilepath ));

        String url  = p.getProperty("URL");
        System.out.println(url); // It is returning me a value corresponding to key "test"
        String driverFilePath = p.getProperty("DRIVER_FILE_PATH");
        System.out.println(driverFilePath);
        String testSuite  = p.getProperty("TEST_SUITE");
        System.out.println(testSuite);
    }
}

MainClass.java

public class MainClass {

    static Properties properties= new Properties();

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        ReadPropertyFile readConfigFile= new ReadPropertyFile();
    }
}

2 个答案:

答案 0 :(得分:0)

将您的配置读取器放在类Method中。 而且你只能在时间使用'main'一次。

  public class ReadPropertyFile{

           public void readFile(){

                // read config

答案 1 :(得分:0)

如果正常工作,请将此代码放入方法中

public class ReadPropertyFile {

 public Properties  loadPropertiess() throws IOException{

// Read configuration properties file

   String projdir = System.getProperty("user.dir");
   String propfilepath = projdir+"\\configuration\\"+"conf.properties";
   Properties p = new Properties();
 p.load(new FileInputStream(propfilepath ));

   String url  = p.getProperty("URL");
  System.out.println(url); // It is returning me a value corresponding to key "test"
  String driverFilePath = p.getProperty("DRIVER_FILE_PATH");
  System.out.println(driverFilePath);
  String testSuite  = p.getProperty("TEST_SUITE");
   System.out.println(testSuite);
   return p;
} }

然后在您的主类

上调用此方法
public class MainClass {

  static Properties properties= null;

  public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub

  ReadPropertyFile readConfigFile= new ReadPropertyFile();

   properties = readConfigFile.loadPropertiess();
   }
}