Skip to content

Instantly share code, notes, and snippets.

@jayeshcp
Last active August 11, 2016 16:43
Show Gist options
  • Save jayeshcp/f55b133230508610ed7e to your computer and use it in GitHub Desktop.
Save jayeshcp/f55b133230508610ed7e to your computer and use it in GitHub Desktop.
Reading .properties file
# App Properties
name=Demo App
author=Jayesh
email=jaycp@gmail.com
/**
* This program reads config.properties file and displays
* all the keys and values
*
* @author Jayesh Chandrapal
* @version 1.0
*/
import java.util.Properties;
import java.io.InputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.FileNotFoundException;
public class ReadProperties {
public static void main(String[] args) {
Properties prop;
try {
prop = new AppProperties().getProps();
// Print properties value by key
System.out.println(prop.getProperty("name"));
System.out.println(prop.getProperty("author"));
System.out.println(prop.getProperty("email"));
// Print properties by iterating through all keys
String key;
Set<String> keys = prop.stringPropertyNames();
Iterator<String> iter = keys.iterator();
while(iter.hasNext()) {
key = iter.next();
System.out.println( key + "=" + prop.getProperty(key) );
}
// Can also print all properties like this
prop.list( System.out );
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
class AppProperties {
public Properties getProps() throws IOException {
Properties prop = new Properties();
String propFileName = "config.properties";
InputStream inputStream = new FileInputStream(propFileName);
if (inputStream != null) {
prop.load(inputStream);
} else {
throw new FileNotFoundException("Property file '" + propFileName + "' not found in the classpath");
}
return prop;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment