import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.Map;
/* In this example our class location4 has 3 fields int,string and Map
where int and String are primitive types but Map is an object
And the map we are using is Hashmap which implements Serializable interface so map will also we serialised .
If there is a field in classes that is not serializable its or responsibility to make it serialized as well*/
public class location implements Serializable {
private final int locationId;
private final String description;
private final Map<String,Integer> exits;
private Long serialVersionUID = 1L;
Then we read and write from this class like below
// private Long serialVersionUID = 1L;
Then an invalid class exception will be thrown in this block of code for our class
catch (InvalidClassException e){
System.out.println("InvalidClass exception "+e.getMessage());
}
As in that case we are trying to read from locations1.dat file to create a location object but since we have
commented that line of code so runtime will say that the object you are reading from location1.dat file
has UID = 1 as we have written that object to locations1.dat before commenting out that line
So runtime will sat that given object has uid1 ,but it will assign uid to location4 at runtime so both objects
are not same anymore so that's why invalid class exception.
public static void main(String[] args) throws IOException {
try (ObjectOutputStream locfile = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream("locations2.dat")));) {
for (location location : locations.values()) {
locfile.writeObject(location);
}
}
}
Reading objects from a file in a static block
static {
try (ObjectInputStream locfile = new ObjectInputStream(new BufferedInputStream(new FileInputStream("locations1.dat")))) {
boolean endOfFile = false;
while(!endOfFile) {
try {
//Please note that here are readingObject using reaObject and we have to cast it type Location
location location = (location) locfile.readObject();
//And once object is created we can access the methods of this class
System.out.println("Read location---> " + location.getLocationId() + " , " + location.getDescription());
}
catch (InvalidClassException e){
System.out.println("InvalidClass exception "+e.getMessage());
}
catch (EOFException e){
endOfFile = true;
}
}
}
catch (IOException e) {
e.printStackTrace();
}
catch (ClassNotFoundException e){
//Please note we are throwing this exception because if we are reading an object from a location.dat file
//but can't find corresponding class in class path
//For example if another class tries to read location.dat file but if that class doesn't contain location class.
System.out.println("ClassNotFoundException "+e.getMessage());
}
}