Advertisement
Guest User

Untitled

a guest
Feb 26th, 2020
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.68 KB | None | 0 0
  1. package Lesson12;
  2.  
  3. import java.io.Serializable;
  4.  
  5. public class Animal implements Serializable {
  6.  
  7. /**
  8. *
  9. */
  10. private static final long serialVersionUID = 1L;
  11. private String name;
  12. private int age;
  13. private transient String color;
  14.  
  15. public Animal(String name, int age, String color) {
  16. this.name = name;
  17. this.age = age;
  18. this.color = color;
  19. }
  20.  
  21. @Override
  22. public String toString() {
  23.  
  24. return name + "-" + age + "-" + color;
  25. }
  26.  
  27. }
  28.  
  29.  
  30.  
  31.  
  32.  
  33. package Lesson12;
  34.  
  35. import java.io.File;
  36. import java.io.FileInputStream;
  37. import java.io.FileOutputStream;
  38. import java.io.ObjectInputStream;
  39. import java.io.ObjectOutputStream;
  40.  
  41. public class Main {
  42.  
  43. public static void main(String[] args) {
  44. Animal dog = new Animal("Arman", 5, "White");
  45. Animal cat = new Animal("Masha", 2, "Grey");
  46. Animal parrot = new Animal("Petya", 1, "Green");
  47. System.out.println("Dog: " + dog);
  48. System.out.println("Cat: " + cat);
  49. System.out.println("Parrot: " + parrot);
  50. try {
  51. File file = new File("vyvod.txt");
  52. FileOutputStream fos = new FileOutputStream(file);
  53. ObjectOutputStream ous = new ObjectOutputStream(fos);
  54. ous.writeObject(dog);
  55. ous.writeObject(cat);
  56. ous.writeObject(parrot);
  57. ous.close();
  58. fos.close();
  59. FileInputStream fis = new FileInputStream(file);
  60. ObjectInputStream ois = new ObjectInputStream(fis);
  61. cat = (Animal) ois.readObject();
  62. parrot = (Animal) ois.readObject();
  63. dog = (Animal) ois.readObject();
  64. ois.close();
  65. fis.close();
  66. System.out.println("Dog: " + dog);
  67. System.out.println("Cat: " + cat);
  68. System.out.println("Parrot: " + parrot);
  69. } catch (Exception e) {
  70. e.printStackTrace();
  71. }
  72.  
  73. }
  74.  
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement