I've decided to make a wrapper class for the java.util.Properties
class since, in its current state, it only allows for storing and reading String
values.
Is there any way I can improve the following code?
public final class Prefs {
private static final Properties properties = new Properties();
private static OutputStream out;
public static final File test = new File("settings.properties");
public static void main(String[] args) throws IOException {
try {
set("hello", "5");
int hello = get("hello", 1337);
System.out.println(hello == 5);
set("hello", "34");
hello = get("hello", 1337);
System.out.println(hello == 34);
remove("hello");
hello = get("hello", 1337);
System.out.println(hello == 1337);
} finally {
save();
}
}
static {
try {
if (!test.exists()) {
test.createNewFile();
}
properties.load(new FileInputStream(test));
out = new FileOutputStream(test);
} catch (IOException e) {
e.printStackTrace();
}
}
public static <T> T get(String key, T defaultValue) {
if (!properties.containsKey(key)) {
return defaultValue;
}
String value = properties.getProperty(key);
if (defaultValue instanceof Long) {
return (T) new Long(value);
} else if (defaultValue instanceof Integer) {
return (T) new Integer(value);
} else if (defaultValue instanceof Short) {
return (T) new Short(value);
} else if (defaultValue instanceof Byte) {
return (T) new Byte(value);
} else if (defaultValue instanceof Double) {
return (T) new Double(value);
} else if (defaultValue instanceof Float) {
return (T) new Float(value);
} else if (defaultValue instanceof Boolean) {
return (T) new Boolean(value);
}
return (T) value;
}
public static void set(String key, String value) {
properties.setProperty(key, "" + value);
}
public static void remove(String key) {
properties.remove(key);
}
private static final ReentrantLock lock = new ReentrantLock();
public static void save() {
lock.lock();
try {
properties.store(out, "");
out.flush();
} catch (Throwable e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}