Monday, April 30, 2018

Read properties from an xml file !!

Using Properties class:
  1. import java.io.File;
  2. import java.io.FileInputStream;
  3. import java.util.Enumeration;
  4. import java.util.Properties;

  5. public class ReadPropertiesXmlFile {
  6. public static void main(String[] args) throws Exception {
  7. File file = new File("D:\\prop.xml");
  8. FileInputStream fileInput = new FileInputStream(file);
  9. Properties properties = new Properties();
  10. properties.loadFromXML(fileInput);
  11. fileInput.close();

  12. Enumeration enuKeys = properties.keys();
  13. while (enuKeys.hasMoreElements()) {
  14. String key = (String) enuKeys.nextElement();
  15. String value = properties.getProperty(key);
  16. System.out.println(key + ": " + value);
  17. }
  18. }
  19. }
Output:
favoriteSeason: spring
favoriteDay: today
favoriteFruit: apple

prop.xml - file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>Here are some favorites</comment>
<entry key="favoriteSeason">spring</entry>
<entry key="favoriteFruit">apple</entry>
<entry key="favoriteDay">today</entry>

</properties>

No comments:

Post a Comment

Blueprint for self-improvement

To learn faster: Make the process fun To understand yourself : Write To understand the world better : Read To build deeper connection : Lis...