Skip to content

Instantly share code, notes, and snippets.

@awwsmm
Last active August 17, 2018 14:10
Show Gist options
  • Save awwsmm/793d10e09d6477f938b5638e371c7623 to your computer and use it in GitHub Desktop.
Save awwsmm/793d10e09d6477f938b5638e371c7623 to your computer and use it in GitHub Desktop.
Load Java program configuration / settings at runtime (key-value pairs)
DEBUG=true
NAME=Yoda
AGE=922
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
// Compile and then run! Change the settings.conf file and rerun without recompiling!
// Settings are updated without needing to recompile.
public class Settings {
public static boolean DEBUG = false;
public static String NAME = "";
public static int AGE = -1;
public static void main (String[] args) {
try (FileInputStream fis = new FileInputStream("settings.conf")) {
Properties props = new Properties();
// load the settings from the configuration file
props.load(fis);
// settings loaded at runtime!
DEBUG = Boolean.parseBoolean(props.get( "DEBUG" ).toString());
NAME = props.get( "NAME" ).toString() ;
AGE = Integer.parseInt( props.get( "AGE" ).toString());
if (DEBUG) {
System.out.println("Settings file successfuly loaded");
System.out.printf("Name: %s%n", NAME);
System.out.printf("Age: %d%n", AGE);
}
} catch(IOException e) {
System.out.println(" !! ERROR: problem reading settings.conf file.");
}
return;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment