Last active
August 29, 2015 14:00
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#sample config file | |
secret=ThisIsMySecret | |
secretNumber=111 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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