Let's create a property file config.properties with below Keys and Values:
browser = mozilla
dept = finance
id = 1234
password = Asdf123
user = userxyz
url = https:\\www.google.com
user = userxyz
//Create a class as below:
public class ReadPropFrom {
public static String readproperties(String enterKey) throws IOException {
String filePath = "C:\\Selenium\\SeleniumProjects\\TutorialProp\\src\\tutorialProp\\config.properties";
File fl = new File(filePath);
FileInputStream fis = new FileInputStream(fl);
Properties prop = new Properties();
prop.load(fis);
String valueForKey = prop.getProperty(enterKey);
return valueForKey;
}
}
// Now call the method in the main method like below:
public class TutProp {
public static void main(String[] args) throws IOException {
ReadPropFrom ss = new ReadPropFrom();
String department = ss.readproperties("dept");
String id = ss.readproperties("id");
System.out.println("department is : "+department );
System.out.println("id is : "+id );
}
}
The output from above main method will be :
department is : finance
id is : 1234
Read from xml file :
public class Practice {
public static void main(String[] args) {
try {
String filePath = System.getProperty("user.dir")+"\\src\\practice\\xmlFile.xml";
File fl = new File(filePath);
FileInputStream fis = new FileInputStream(fl);
Properties prop = new Properties();
prop.loadFromXML (fis);
String valueForKey = prop.getProperty("NumberTwo");
System.out.println("valueForKey is "+valueForKey );
}
catch (Exception e ) {
e.printStackTrace();
}
}
}
Answer:
the value for the key "NumberTwo" will be returned.
No comments:
Post a Comment