Last active
April 23, 2018 21:02
-
-
Save listopad/4e0fec7db5ea911ae5caed5b598362f5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package chi.utils; | |
import java.io.*; | |
import java.util.HashMap; | |
import java.util.Properties; | |
public class ConfigManager { | |
private final File config_file; | |
private static HashMap<String, String> preferences; | |
private Properties props; | |
public ConfigManager() { | |
preferences = new HashMap<>(); | |
this.config_file = new File("./resources/config.properties"); | |
this.props = new Properties(); | |
OpenProperties(); | |
LoadProperties(); | |
} | |
private void OpenProperties() { | |
try (FileInputStream reader = new FileInputStream(config_file)) { | |
props.load(reader); | |
System.out.println(config_file.getName()); | |
} catch (FileNotFoundException e) { | |
e.printStackTrace(); | |
System.err.format("Properties file {0}%s not found.", config_file.getName()); | |
System.exit(1); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
System.err.format("Properties file {0}%s can not be loaded.", config_file.getName()); | |
System.exit(1); | |
} finally { | |
System.out.println("Properties file was successfully opened."); | |
} | |
} | |
private void LoadProperties() { | |
for (final String name : props.stringPropertyNames()) | |
preferences.put(name, props.getProperty(name)); | |
} | |
public String getAttribute(String attributeName) { | |
String attribute = preferences.get(attributeName); | |
if (attribute != null) { | |
return attribute; | |
} else { | |
System.out.println("Unable to read attribute, keyword not found."); | |
return null; | |
} | |
} | |
public void setAttribute(String attributeName, String value) throws FileNotFoundException { | |
String attribute = preferences.get(attributeName); | |
if (attribute != null) { | |
props.setProperty(attributeName, value); | |
try (FileOutputStream writer = new FileOutputStream(config_file)) { | |
props.store(writer, ""); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} else { | |
System.out.println("Unable to set attribute, keyword not found."); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment