1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
|
use core:io;
use util:serialize;
class Settings : serializable {
User user = User("Filip", 30);
Str country = "Sweden";
void toS(StrBuf to) : override {
to << "{ user: " << user << ", country: " << country << " }";
}
}
class User : serializable {
Str name;
Nat age;
init(Str name, Nat age) {
init { name = name; age = age; }
}
void toS(StrBuf to) : override {
to << "{ name: " << name << ", age: " << age << " }";
}
}
Url settingsUrl() {
return cwdUrl / "settings.dat";
}
void save() {
Settings settings;
Url saveTo = settingsUrl();
ObjOStream out(saveTo.write());
settings.write(out);
out.close();
print("Saved to: ${saveTo}");
}
void text() {
Url loadFrom = settingsUrl();
TextObjStream in(loadFrom.read());
Str textRepr = in.read();
print("Settings as text:");
print(textRepr);
}
void load() {
Url loadFrom = settingsUrl();
ObjIStream in(loadFrom.read());
print("Loading settings from: ${loadFrom}...");
try {
Settings settings = Settings:read(in);
print("Success: ${settings}");
} catch (SerializationError e) {
print("Failed: ${e.message}");
}
}
|