Last active
May 24, 2019 08:58
-
-
Save HyCraftHD/66e140f6ca6f952cf84d0292364f4770 to your computer and use it in GitHub Desktop.
Easy Json configuration with Gson
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 info.u_team.music_player.musicplayer; | |
import java.io.*; | |
import java.nio.file.*; | |
import org.apache.logging.log4j.*; | |
import com.google.gson.*; | |
public class GsonConfig { | |
private static final Logger logger = LogManager.getLogger(); | |
private final Gson gson; | |
private final Path path; | |
private OurObject obj; | |
public GsonConfig(Path path) { | |
gson = new GsonBuilder().setPrettyPrinting().create(); | |
this.path = path | |
} | |
public void loadFromFile() { | |
try { | |
if (!Files.exists(path)) { | |
obj = new OurObject(); | |
writeToFile(); | |
} else { | |
try (BufferedReader reader = Files.newBufferedReader(path)) { | |
obj = gson.fromJson(reader, OurObject.class); | |
} catch (IOException ex) { | |
throw ex; | |
} | |
} | |
} catch (IOException ex) { | |
logger.error("Could not ready json file at " + path, ex); | |
} | |
} | |
public void writeToFile() { | |
try (BufferedWriter writer = Files.newBufferedWriter(path)) { | |
gson.toJson(obj, writer); | |
} catch (IOException ex) { | |
logger.error("Could not write json file at " + path, ex); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment