object input stream java

Solutions on MaxInterview for object input stream java by the best coders in the world

showing results for - "object input stream java"
Lucia
03 Jul 2019
1import java.io.FileInputStream;
2import java.io.FileOutputStream;
3import java.io.ObjectInputStream;
4import java.io.ObjectOutputStream;
5import java.io.Serializable;
6
7class Dog implements Serializable {
8
9    String name;
10    String breed;
11
12    public Dog(String name, String breed) {
13        this.name = name;
14        this.breed = breed;
15    }
16}
17
18class Main {
19    public static void main(String[] args) {
20
21        // Creates an object of Dog class
22        Dog dog1 = new Dog("Tyson", "Labrador");
23
24        try {
25            FileOutputStream fileOut = new FileOutputStream("file.txt");
26
27            // Creates an ObjectOutputStream
28            ObjectOutputStream objOut = new ObjectOutputStream(fileOut);
29
30            // Writes objects to the output stream
31            objOut.writeObject(dog1);
32
33            // Reads the object
34            FileInputStream fileIn = new FileInputStream("file.txt");
35            ObjectInputStream objIn = new ObjectInputStream(fileIn);
36
37            // Reads the objects
38            Dog newDog = (Dog) objIn.readObject();
39
40            System.out.println("Dog Name: " + newDog.name);
41            System.out.println("Dog Breed: " + newDog.breed);
42
43            objOut.close();
44            objIn.close();
45        }
46
47        catch (Exception e) {
48            e.getStackTrace();
49        }
50    }
51}
52