package com.javarush.task.task20.task2014; import java.io.*; import java.text.SimpleDateFormat; import java.util.Date; /* Serializable Solution СеÑиализÑйÑе клаÑÑ Solution. ÐодÑмайÑе, какие Ð¿Ð¾Ð»Ñ Ð½Ðµ нÑжно ÑеÑиализоваÑÑ, помеÑиÑÑ Ð½ÐµÐ½ÑжнÑе Ð¿Ð¾Ð»Ñ â transient. ÐбÑÐµÐºÑ Ð²Ñегда должен ÑодеÑжаÑÑ Ð°ÐºÑÑалÑнÑе иÑоговÑе даннÑе. ÐеÑод main не ÑÑаÑÑвÑÐµÑ Ð² ÑеÑÑиÑовании. ÐапиÑаÑÑ ÐºÐ¾Ð´ пÑовеÑки ÑамоÑÑоÑÑелÑно в меÑоде main: 1) ÑоздаÑÑ Ñайл, оÑкÑÑÑÑ Ð¿Ð¾Ñок на ÑÑение (input stream) и на запиÑÑ(output stream) 2) ÑоздаÑÑ ÑкземплÑÑ ÐºÐ»Ð°ÑÑа Solution - savedObject 3) запиÑаÑÑ Ð² поÑок на запиÑÑ savedObject (ÑбедиÑеÑÑ, ÑÑо они Ñам дейÑÑвиÑелÑно еÑÑÑ) 4) ÑоздаÑÑ Ð´ÑÑгой ÑкземплÑÑ ÐºÐ»Ð°ÑÑа Solution Ñ Ð´ÑÑгим паÑамеÑÑом 5) загÑÑзиÑÑ Ð¸Ð· поÑока на ÑÑение обÑÐµÐºÑ - loadedObject 6) пÑовеÑиÑÑ, ÑÑо savedObject.string Ñавна loadedObject.string 7) обÑабоÑаÑÑ Ð¸ÑклÑÑÐµÐ½Ð¸Ñ */ public class Solution implements Serializable { private static final long serialVersionUID = -6356653558390364307L; public static void main(String[] args) { ObjectOutputStream oos = null; try { oos = new ObjectOutputStream(new FileOutputStream("20-07-04.txt")); } catch (IOException e) { e.printStackTrace(); } Solution savedObject = new Solution(18); try { assert oos != null; oos.writeObject(savedObject); oos.flush(); oos.close(); } catch (IOException e) { e.printStackTrace(); } ObjectInputStream ois = null; try { ois = new ObjectInputStream(new FileInputStream("20-07-04.txt")); } catch (IOException e) { e.printStackTrace(); } Solution loadedObject = null; try { loadedObject = (Solution) ois.readObject(); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } System.out.println(savedObject.toString()); System.out.println(loadedObject.toString()); System.out.println(savedObject.string.equals(loadedObject.string)); } private transient final String pattern = "dd MMMM yyyy, EEEE"; //ÑÑо важно!!! private transient Date currentDate; private transient int temperature; String string; public Solution(int temperature) { this.currentDate = new Date(); this.temperature = temperature; string = "Today is %s, and current temperature is %s C"; SimpleDateFormat format = new SimpleDateFormat(pattern); this.string = String.format(string, format.format(currentDate), temperature); } @Override public String toString() { return this.string; } }