Skip to content

Instantly share code, notes, and snippets.

@mariuswatz
Last active August 29, 2015 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mariuswatz/11081115 to your computer and use it in GitHub Desktop.
Save mariuswatz/11081115 to your computer and use it in GitHub Desktop.
How to use java.util.Properties to store config parameters in an external file.
#sample config file
secret=ThisIsMySecret
secretNumber=111
/*
Marius Watz, April 2014
http://workshop.evolutionzone.com
How to load a config file using the java.util.Properties class.
Useful for sketches that require login/password or API secrets.
*/
import java.util.*;
import java.io.FileInputStream;
HashMap<String, String> conf;
String filename="config.txt";
void setup() {
conf=confRead(filename);
// print all keys and values
println("Config: "+filename+" ("+conf.keySet().size()+" keys)");
println("---------------");
for (String s:conf.keySet()) {
println("\tkey: '"+s+"' = '"+confGet(s)+"'");
}
println("---------------\n");
println(confGet("NoSuchKey"));
}
String confGet(String key) {
if(conf.containsKey(key)) return conf.get(key);
println("'"+key+"' not found");
return null;
}
HashMap<String, String> confRead(String filename) {
HashMap<String, String> map=new HashMap<String, String>();
Properties config;
try {
config=new Properties();
config.load(new FileInputStream(sketchPath(filename )));
Enumeration<String> keys=(Enumeration<String>)config.propertyNames();
while (keys.hasMoreElements ()) {
String s=keys.nextElement();
map.put(s, config.getProperty(s));
}
}
catch(Exception e) {
e.printStackTrace();
}
return map;
}
void draw() {
exit();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment