001package com.studentgui.apphelpers; 002 003import java.io.IOException; 004import java.io.InputStream; 005import java.io.OutputStream; 006import java.nio.file.Files; 007import java.nio.file.Path; 008import java.util.Properties; 009 010/** 011 * Lightweight settings persistence for simple key/value preferences. 012 */ 013public final class Settings { 014 private static final Path SETTINGS_FILE = Helpers.APP_HOME.resolve("app.properties"); 015 private static final Properties props = new Properties(); 016 private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(Settings.class); 017 018 static { 019 // load existing if present 020 try (InputStream in = Files.exists(SETTINGS_FILE) ? Files.newInputStream(SETTINGS_FILE) : null) { 021 if (in != null) { 022 props.load(in); 023 } 024 } catch (IOException ioe) { 025 LOG.debug("Could not load settings from {}", SETTINGS_FILE, ioe); 026 } 027 } 028 029 private Settings() { throw new AssertionError(); } 030 031 /** 032 * Get a persisted setting value or return a default when missing. 033 * 034 * @param key setting key 035 * @param def default value when key is absent 036 * @return stored value or default 037 */ 038 public static String get(final String key, final String def) { 039 return props.getProperty(key, def); 040 } 041 042 /** 043 * Store a setting value and persist to disk immediately. 044 * 045 * @param key setting key 046 * @param value setting value (null treated as empty string) 047 */ 048 public static void put(final String key, final String value) { 049 props.setProperty(key, value == null ? "" : value); 050 // persist immediately 051 try (OutputStream out = Files.newOutputStream(SETTINGS_FILE)) { 052 props.store(out, "application settings"); 053 } catch (IOException ioe) { 054 LOG.debug("Could not persist settings to {}", SETTINGS_FILE, ioe); 055 } 056 } 057}