Tutorial Flat File Generic Save/Load

Discussion in 'Resources' started by ForbiddenSoul, Dec 31, 2020.

Thread Status:
Not open for further replies.
  1. Offline

    ForbiddenSoul

    FlatFile.java:
    Code:JAVA
    1. import java.io.FileInputStream;
    2. import java.io.FileOutputStream;
    3. import java.io.IOException;
    4. import java.io.Serializable;
    5. import java.util.zip.GZIPInputStream;
    6. import java.util.zip.GZIPOutputStream;
    7.  
    8. import org.bukkit.util.io.BukkitObjectInputStream;
    9. import org.bukkit.util.io.BukkitObjectOutputStream;
    10.  
    11. public class FlatFile {
    12. public static <T extends Serializable> boolean save(String filePath, T object) {
    13. try {
    14. BukkitObjectOutputStream out = new BukkitObjectOutputStream(new GZIPOutputStream(new FileOutputStream(filePath)));
    15. out.writeObject(object);
    16. out.close();
    17. return true;
    18. } catch (IOException e) {
    19. return false;
    20. }
    21. }
    22. public static <T extends Serializable> T load(String filePath){
    23. try {
    24. BukkitObjectInputStream in = new BukkitObjectInputStream(new GZIPInputStream(new FileInputStream(filePath)));
    25. T object = (T) in.readObject();
    26. in.close();
    27. return object;
    28. return null;
    29. }
    30. }
    31. }

    Usage:
    Code:JAVA
    1. // Objects you are saving and loading must implement/extend Serializable or a Compilation Error will occur
    2. FlatFile.save(plugin.getDataFolder() + "/fileName.extension", objectToSave);
    3. // You must ensure that the data stored in the file being loaded corresponds to the object being loaded back or a Runtime Error will occur
    4. objectToLoad = FlatFile.load(plugin.getDataFolder() + "/fileName.extension");
     

    Attached Files:

    Last edited: Dec 31, 2020
Thread Status:
Not open for further replies.

Share This Page