Class File

java.lang.Object
org.openpatch.scratch.save.File

public class File extends Object
Saves objects as JSON files and loads them again: their public fields and bean properties (getters and setters), with lists, maps, arrays, enums and nested objects.

Usage examples:

// Save an object as JSON
File.save("/path/to/file.json", myObject);

// Load an object from JSON
MyClass obj = File.load("/path/to/file.json", MyClass.class);

Note: The file paths can be absolute or relative. A relative path is relative to the working directory; a file that is only on the classpath (inside a jar) is read from there.

For save games, SaveData is safer: it keeps the last save when writing fails and stores in the player's own folder.

  • Constructor Summary

    Constructors
    Constructor
    Description
     
  • Method Summary

    Modifier and Type
    Method
    Description
    static <T> T
    load(String path, Class<T> cls)
    Loads an object of the specified class from a file at the given path.
    static <T> T
    loadOrCreate(String path, Class<T> cls)
    Loads an object of the specified class from a file at the given path, or creates a new one if the file does not exist.
    static <T> void
    save(String path, T obj)
    Saves the given object as a JSON file at the specified path.

    Methods inherited from class Object

    equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
  • Constructor Details

    • File

      public File()
  • Method Details

    • save

      public static <T> void save(String path, T obj)
      Saves the given object as a JSON file at the specified path.
      Type Parameters:
      T - the type of the object to be saved
      Parameters:
      path - the path where the object should be saved
      obj - the object to be saved
    • load

      public static <T> T load(String path, Class<T> cls)
      Loads an object of the specified class from a file at the given path.
      Type Parameters:
      T - the type of the object to be loaded
      Parameters:
      path - the path to the file from which the object is to be loaded
      cls - the class of the object to be loaded
      Returns:
      the loaded object of the specified class
    • loadOrCreate

      public static <T> T loadOrCreate(String path, Class<T> cls)
      Loads an object of the specified class from a file at the given path, or creates a new one if the file does not exist.
      Type Parameters:
      T - the type of the object to be loaded
      Parameters:
      path - the path to the file from which the object is to be loaded
      cls - the class of the object to be loaded
      Returns:
      the loaded object of the specified class, or a new instance if the file does not exist