0

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??

Ted pottel
  • 6,869
  • 21
  • 75
  • 134
  • [Serialization](http://docs.oracle.com/javase/7/docs/platform/serialization/spec/serialTOC.html) – gtgaxiola Mar 10 '15 at 13:18
  • Note that doing that in C is *very* brittle - and vanilla binary serialization is pretty brittle in Java, too... – Jon Skeet Mar 10 '15 at 13:19
  • possible duplicate of [Dumping a java object's properties](http://stackoverflow.com/questions/603013/dumping-a-java-objects-properties) – emin Mar 10 '15 at 13:20

2 Answers2

1

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

Vish
  • 832
  • 7
  • 21
1

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();
user1438038
  • 5,821
  • 6
  • 60
  • 94