java-commons/src/main/java/de/nclazz/commons/util/PropertyProvider.java

68 lines
1.7 KiB
Java

package de.nclazz.commons.util;
import lombok.SneakyThrows;
import java.io.InputStream;
import java.io.Writer;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;
public class PropertyProvider {
private final Properties properties;
public PropertyProvider(Properties defaults) {
this.properties = new Properties(defaults);
}
public PropertyProvider() {
this.properties = new Properties();
}
public Optional<String> getProperty(String key) {
return Optional.ofNullable(this.properties.getProperty(key));
}
public Optional<String> putProperty(String key, Object value) {
String last = this.properties.getProperty(key);
if(value == null) {
this.properties.remove(key);
}else {
this.properties.setProperty(key, value.toString());
}
return Optional.ofNullable(last);
}
public void clear() {
this.properties.clear();
}
@SneakyThrows
public void write(Writer writer) {
for(Map.Entry<Object, Object> entry : this.properties.entrySet()) {
String key = entry.getKey().toString();
Object value = entry.getValue();
String valueStr = value != null ? value.toString() : "";
writer.append(key)
.append(" = ")
.append(valueStr)
.append(System.lineSeparator());
}
}
/**
* Loads the properties from given {@code stream}.
* The stream remains open after loading.
* @param stream InputStream to load
*/
@SneakyThrows
public void load(InputStream stream) {
this.properties.load(stream);
}
}