Friday, July 2, 2010

Java System properties Examples


1. How to load a properties file into System properties
1. How to Retrieve all System properties

1. How to load a properties file into System properties
This program loads all properties from a properties file directly into System properties

package io;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

public class SystemPropertiesExample {

public static void main(String[] args) {
FileInputStream fis = null;
try {

Properties props = new Properties();
fis = new FileInputStream(new File("c:/temp/config.properties"));
props.load(fis);
System.setProperties(props);

} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fis.close();
fis = null;
} catch (IOException e) {
e.printStackTrace();
}
}

}
}


2. How to Retrieve all System properties

package io;

import java.util.Enumeration;
import java.util.Properties;

public class SystemPropertiesExample {

public static void main(String[] args) {

Properties props = System.getProperties();

// Enumerate all system properties
Enumeration enumu = props.keys();
while (enumu.hasMoreElements()) {
String propName = (String) enumu.nextElement();
String propValue = (String) props.get(propName);
System.out.println(propName +" :: "+propValue);
}
}
}

No comments:

Post a Comment