Skip to content

Instantly share code, notes, and snippets.

@knjk04
Created June 30, 2020 11:36
Show Gist options
  • Save knjk04/0f16f722d898c722ca9707c2629adb38 to your computer and use it in GitHub Desktop.
Save knjk04/0f16f722d898c722ca9707c2629adb38 to your computer and use it in GitHub Desktop.
As part of the Property Map article
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
public class PropertiesExample {
public static void main(String[] args) {
// Defining a properties instance
System.out.println("--- Defining a properties instance ---");
Properties props = new Properties();
props.setProperty("version", "1.4.2");
props.setProperty("author", "Joe Bloggs");
// Saving to a file
System.out.println("\n--- Saving to a file ---");
try {
FileOutputStream out = new FileOutputStream("conf.properties");
props.store(out, "Configuration properties");
} catch (IOException e) {
e.printStackTrace();
}
// Reading from a file
System.out.println("\n--- Reading from a file ---");
Properties loaded = new Properties();
try {
FileInputStream in = new FileInputStream("conf.properties");
loaded.load(in);
// Retrieving value (no default)
String author = loaded.getProperty("author");
System.out.println("Author: " + author);
// Retrieving value with a default
String noKey = loaded.getProperty("location", "Stockholm");
System.out.println("Default key: " + noKey);
} catch (IOException e) {
e.printStackTrace();
}
// Retrieving values: default properties with a secondary property map
System.out.println("\n--- Retrieving values using a secondary property map---");
Properties defaultProps = new Properties();
defaultProps.setProperty("version", "v1.0.0");
defaultProps.setProperty("author", "Clark Kent");
Properties props2 = new Properties(defaultProps);
String version = props2.getProperty("version");
System.out.println("Version: " + version);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment