Using Java Properties File

Many programmers use properties files for keeping configuration parameters (DB Server IP etc.)

Here is a sample class code for accessing configuration parameters from a properties file. You can pass JVM parameter like this :

java -DMyPropertiesFile=/usr/local/java/proj/myconfig.properties MyClass


package javacream;

import java.io.InputStream;
import java.util.Properties;

public class AppProperties {
private static Properties prop;

static {
initiate();
}

protected static void initiate() {
try {
//Pass Java VM following arguement
// -DMyPropertiesFile="[PATH]/[PROPERTIESFILENAME]"

prop = new Properties();

String propertiesFile = System.getProperty("MyPropertiesFile");

if (propertiesFile == null) {
System.out
.println("Could not find content.properties property in System Properties.");
System.out
.println("This property file is needed for the application to operate.");
System.out
.println("Send this parameter as -DMyPropertiesFile=%FILENAME% to java vm.");

propertiesFile = "myconfiguration.properties";

System.out
.println("Setting properties file name to default value "
+ propertiesFile);

}

try {
InputStream is = new java.io.FileInputStream(propertiesFile);

prop.load(is);
} catch (Exception e) {
e.printStackTrace();

System.out.println("Could not read or find MyPropertiesFile");
System.out
.println("This property file is needed for the application to operate.");
System.out
.println("Send this parameter as -MyPropertiesFile=%FILENAME% to java vm.");
return;
}
} catch (Throwable t) {
t.printStackTrace();

return;
}

}

public static String get(String key) {
String value = prop.getProperty(key);
if ((value == null) && !prop.containsKey(key)) {
System.out.println("Could not find the key " + key
+ " in Properties file.");

}
return (value);
}

public static String get(String key, String defaultValue) {
String value = prop.getProperty(key);

if ((value == null) && !prop.containsKey(key)) {
System.out.println("Could not find the key " + key
+ " in Properties file, using default value");
}

return (prop.getProperty(key, defaultValue));

}

public static void main(String[] args) {
System.out.println(AppProperties.get("UserName"));
}

}

Comments

Popular posts from this blog

Connect via SSH without a password from MacOS to Linux with an SSHKEY

Read and Write Files in Java

Install Mac OS on windows laptop