loads persisted variable "name" from disk, if you can, otherwise uses the value supplied by "def" At exit this variable will be saved to disk. So for mutable types "T" the final variable will be automatically saved and restored across sessions. For non-mutable types you'll want to use the three
(String name, Supplier<T> def)
| 47 | * sessions. For non-mutable types you'll want to use the three argument version of persist. |
| 48 | */ |
| 49 | static public <T extends Serializable> T persist(String name, Supplier<T> def) { |
| 50 | if (dir == null) return def.get(); |
| 51 | |
| 52 | try (ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(new File(dir + name))))) { |
| 53 | T ro = (T) ois.readObject(); |
| 54 | return hook(name, ro, () -> ro); |
| 55 | } catch (Throwable e) { |
| 56 | e.printStackTrace(); |
| 57 | T x = def.get(); |
| 58 | try (ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(new File(dir + name))))) { |
| 59 | oos.writeObject(x); |
| 60 | } catch (Throwable e2) { |
| 61 | e2.printStackTrace(); |
| 62 | } |
| 63 | return hook(name, x, () -> x); |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | /** |
| 68 | * loads persisted variable "name" from disk, if you can, otherwise uses the value supplied by "def" |
no test coverage detected