Skip to content

Instantly share code, notes, and snippets.

@Tarrasch
Last active May 17, 2016 07:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Tarrasch/1973811e406968fea7c7d4eb574b1caf to your computer and use it in GitHub Desktop.
Save Tarrasch/1973811e406968fea7c7d4eb574b1caf to your computer and use it in GitHub Desktop.
Saving and loading objects from a Path in Java
// These methods could be pasted in a class.
// I found these two implementations to be better than what was provided in various library-provided util classes. Because these methods mute no exceptions.
// These version are also not dependent if you use files from disk or not.
private static void writeObjectToDisk(Object o, Path p) throws IOException {
try (OutputStream os = Files.newOutputStream(p);
ObjectOutputStream oos = new ObjectOutputStream(os)) {
oos.writeObject(o);
}
}
private static Object loadObjectFromDisk(Path p) throws IOException, ClassNotFoundException {
try (InputStream is = Files.newInputStream(p);
ObjectInputStream ois = new ObjectInputStream(is)) {
return ois.readObject();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment