Last active
May 17, 2016 07:35
-
-
Save Tarrasch/1973811e406968fea7c7d4eb574b1caf to your computer and use it in GitHub Desktop.
Saving and loading objects from a Path in Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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