Properties Load Store Config Roundtrip
Round-trip service configuration through Properties store and load, with getProperty's two-arg form supplying defaults for absent keys.
Code
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Properties;
public class ConfigRoundtrip {
public static void main(String[] args) throws IOException {
Properties config = new Properties();
config.setProperty("pool.size", "8");
config.setProperty("retry.max", "3");
// store:写出带 # 注释与时间戳注释的 key=value 文本
StringWriter out = new StringWriter();
config.store(out, "service connection settings");
System.out.println("stored lines: " + out.toString().lines().count());
// load:从同一格式读回
Properties loaded = new Properties();
loaded.load(new StringReader(out.toString()));
System.out.println("pool.size=" + loaded.getProperty("pool.size"));
System.out.println("retry.max=" + loaded.getProperty("retry.max"));
// 双参 getProperty:缺失键兜底默认值
System.out.println("timeout.ms default: " + loaded.getProperty("timeout.ms", "1000"));
}
}How it works
Properties Load Store Config Roundtrip comes down to the class ConfigRoundtrip.
Putting it to use
The demo output is labeled (stored lines:, pool.size=, retry.max=), so every printed line maps back to its originating operation.
Core lines
config.store(out, "service connection settings");
loaded.load(new StringReader(out.toString()));
StringWriter out = new StringWriter();
Interactive Tools for This Topic
Properties File ParserParse Java .properties files with comments, continuations, separators, and escapes, then emit clean JSON.Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.
FAQ
- What does Properties Load Store Config Roundtrip print when run?
- The script runs standalone; its 4 labeled outputs include `stored lines:`, `pool.size=`, `retry.max=`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.