Last active
February 21, 2020 05:39
-
-
Save Erezbiox1/beb8653449adff281867579863db1937 to your computer and use it in GitHub Desktop.
Simple Object Serializer
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
import java.io.*; | |
import java.util.HashMap; | |
import java.util.Map; | |
/** | |
* Created by Erezbiox1 on 17/05/2017. | |
* (C) 2016 Erez Rotem All Rights Reserved. | |
*/ | |
public class Serializer { | |
private final Map<String, Object> objects = new HashMap<>(); | |
private final String folderLocation; | |
private final String suffix; | |
public Serializer(String folderLocation, String suffix) { | |
this.folderLocation = folderLocation; | |
this.suffix = suffix; | |
} | |
public Serializer(String folderLocation) { | |
this(folderLocation, "data"); | |
} | |
public <T> T loadOrAdd(String key, Object object) { | |
T newObject = loadRaw(getLocation(key)); | |
if (newObject == null) | |
objects.put(key, object); | |
else objects.put(key, newObject); | |
return load(key); | |
} | |
public <T> boolean doesHave(String key){ | |
T object = loadRaw(getLocation(key)); | |
if(object == null) | |
return false; | |
objects.put(key, object); | |
return true; | |
} | |
public <T> T load(String key) { | |
return (T) objects.get(key); | |
} | |
public void add(String key, Object object){ | |
objects.put(key, object); | |
} | |
public void saveAll() { | |
objects.forEach((key, object) -> { | |
saveRaw(getLocation(key), object); | |
}); | |
} | |
@Deprecated | |
public static void saveRaw(String fileName, Object object) { | |
try { | |
FileOutputStream fileOut = new FileOutputStream(fileName); | |
ObjectOutputStream objectOut = new ObjectOutputStream(fileOut); | |
objectOut.writeObject(object); | |
objectOut.close(); | |
fileOut.close(); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
} | |
@Deprecated | |
public static <T> T loadRaw(String fileName) { | |
T object = null; | |
try { | |
FileInputStream fileIn = new FileInputStream(fileName); | |
ObjectInputStream objectIn = new ObjectInputStream(fileIn); | |
object = (T) objectIn.readObject(); | |
objectIn.close(); | |
fileIn.close(); | |
} catch (FileNotFoundException ignore) { | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
return object; | |
} | |
private String getLocation(String fileName) { | |
String location = folderLocation + "/" + fileName + "." + suffix; | |
createFolders(location); | |
return location; | |
} | |
private void createFolders(String location) { | |
File folder = new File(location).getParentFile(); | |
if (!folder.isDirectory() || !folder.exists()) | |
folder.mkdirs(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment