Another thing that I would like to add, that might not be clear. That code using the ObjectOutputStream and ObjectInputStream, is best used to save whole objects. Not only int numbers: out.writeInt(1)
If you look at the API, there is a method: ObjectOutputStream.writeObject(Object obj)
that takes as argument any object. So if you have a class with many attributes, you can call only that method and that's it.
For reading just call: ObjectInputStream.readObject()
. It returns an Object and all you have to do is cast to the right one.
These classes have examples:
ObjectOutputStream
ObjectInputStream
Remember in order to do that, the class that you are trying to save must implement the Serializable interface. And if your class has other classes as attributes, those must also implement that interface:
class CustomObject1 implements java.io.Serializable {
private CustomObject2 cust = null;
private String s = null;
private int i = 0;
}
class CustomObject2 implements java.io.Serializable {
}
If you look at the API of String class you will see that it already implements that interface. And primitive types "int" can be written with no extra work. So you are good to go.
That means that not all classes of the JAVA API can be written with that way if they don't implement Serializable.
You can write collections as well:
SomeObject [] array = new SomeObject[5];
....
....
File f = new File("filename");
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(f)); …