Skip to content

Instantly share code, notes, and snippets.

@trplll
Created September 18, 2016 20:57
Show Gist options
  • Save trplll/1384b935f21a5c2bd9c56964d4786446 to your computer and use it in GitHub Desktop.
Save trplll/1384b935f21a5c2bd9c56964d4786446 to your computer and use it in GitHub Desktop.
Using xml property files for java program
package com.company;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Properties;
public class Main {
public static void main(String[] args) {
try {
Properties defaultProps = new Properties();
try(InputStream inputStream = Main.class.getResourceAsStream("MyDefaultValues.xml")) {
defaultProps.loadFromXML(inputStream);
}
Properties userProps = new Properties(defaultProps);
loadUserProps(userProps);
String welcomeMessage = userProps.getProperty("welcomeMessage");
String farewellMessage = userProps.getProperty("farewellMessage");
System.out.println(welcomeMessage);
System.out.println(farewellMessage);
if(userProps.getProperty("isFirstRun").equalsIgnoreCase("Y")) {
userProps.setProperty("welcomeMessage", "Welcome back");
userProps.setProperty("farewellMessage", "Things will be familiar now");
userProps.setProperty("isFirstRun", "N");
saveUserProps(userProps);
}
} catch (IOException e) {
System.out.println("Exception <" + e.getClass().getSimpleName() + "> " + e.getMessage());
}
}
private static Properties loadUserProps(Properties userProps) throws IOException{
Path userFile = Paths.get("userValues.xml");
if(Files.exists(userFile)) {
try(InputStream inputStream = Files.newInputStream(userFile)) {
userProps.loadFromXML(inputStream);
}
}
return userProps;
}
private static void saveUserProps(Properties userProps) throws IOException {
try(OutputStream outputStream = Files.newOutputStream(Paths.get("userValues.xml"))) {
userProps.storeToXML(outputStream, null);
}
}
}
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<entry key="isFirstRun">Y</entry>
<entry key="welcomeMessage">Hello newcomer</entry>
<entry key="farewellMessage">It'll all be different soon</entry>
</properties>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment