java how to get input stream code example
Example: object input stream java
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class Dog implements Serializable {
String name;
String breed;
public Dog(String name, String breed) {
this.name = name;
this.breed = breed;
}
}
class Main {
public static void main(String[] args) {
Dog dog1 = new Dog("Tyson", "Labrador");
try {
FileOutputStream fileOut = new FileOutputStream("file.txt");
ObjectOutputStream objOut = new ObjectOutputStream(fileOut);
objOut.writeObject(dog1);
FileInputStream fileIn = new FileInputStream("file.txt");
ObjectInputStream objIn = new ObjectInputStream(fileIn);
Dog newDog = (Dog) objIn.readObject();
System.out.println("Dog Name: " + newDog.name);
System.out.println("Dog Breed: " + newDog.breed);
objOut.close();
objIn.close();
}
catch (Exception e) {
e.getStackTrace();
}
}
}