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
   |  
	public static void saveObject(Object obj, String fileName)
			throws IOException {
		Path file = Paths.get(fileName);
		Files.deleteIfExists(file);
		Files.createFile(file);
 
		try (FileOutputStream fos = new FileOutputStream(file.toFile());
				ObjectOutputStream oos = new ObjectOutputStream(fos);) {
			oos.writeObject(obj);
			oos.flush();
		} catch (IOException c) {
			System.out.println(c.getMessage());
			throw c;
		}
	}
 
	public static Object readObject(Path file) throws ClassNotFoundException, ClassCastException, IOException{
		return readObject(file, Object.class.getClass());
	}
 
	public static <T> T readObject(Path file, Class<T> clazz) throws IOException, ClassNotFoundException, ClassCastException{
		T returnObj = null;
		try (FileInputStream fis = new FileInputStream(file.toFile());
				ObjectInputStream ois = new ObjectInputStream(fis);) {
			returnObj = (T) ois.readObject();
		} catch (Exception c) {
			System.out.println(c.getMessage());
			displaySuppressed(c.getSuppressed());
			throw c;
		}
 
		return returnObj;
	}
 
	private static void displaySuppressed(Throwable... t){
		for (Throwable thr : t){
			System.out.println("suppressed : " + thr.getMessage());
		}
	} | 
Partager