Ted pottel
Ted pottel

Reputation: 6983

Is there a way to save the state of a object?

In c I could simply do something like fwrite(file,&object,(sizeof object)); to save all the verbals in the object. Is there a way to do this in java??

Upvotes: 0

Views: 88

Answers (2)

user1438038
user1438038

Reputation: 6059

Make your class implement the Serializable interface, then you can serialize objects using an ObjectOutputStream:

public class Person implements Serializable {
  public String name = "";
  public int age = 0;
}

Serialization:

Person p = new Person();
p.name = "Foobar";
p.age = 42;

ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("C:/test.txt"));
oos.writeObject(p);
oos.close();

Deserialization:

ObjectInputStream ois = new ObjectInputStream(new FileInputStream("C:/test.txt"));
Person p = (Person)ois.readObject();
System.out.println(p.name + " is " + p.age + " years of age.");
ois.close();

Upvotes: 1

Vish
Vish

Reputation: 842

Yes, you can save the state of object in Java using Serialization or Externalization.

Upvotes: 1

Related Questions