Neste exemplo vamos explicar como funciona o método writeObject e readObject.
Dado o código:
import java.io.*;
public class Teste {
public static void main(String[] args) throws IOException {
try{
Dog d = new Dog(“Pedro”, 34, 88);
System.out.println(d);
FileOutputStream fos = new FileOutputStream(“dog.cog”);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(d);
oos.close();
FileInputStream fis = new FileInputStream(“dog.cog”);
ObjectInputStream ois = new ObjectInputStream(fis);
d = (Dog)ois.readObject();
ois.close();
System.out.println(d);
}catch(ClassNotFoundException e){e.printStackTrace();}
}
}
class Dog implements Serializable{
private transient int peso;
private transient int idade;
private String nome;
public Dog(String nome, int idade, int peso){
this.nome = nome;
this.idade = idade;
this.peso = peso;
}
public String getNome(){
return this.nome;
}
public int getIdade(){
return this.idade;
}
public int getPeso(){
return this.peso;
}
private void writeObject(ObjectOutputStream os){
try {
os.defaultWriteObject();
os.writeInt(this.idade);
os.writeInt(this.peso);
} catch(Exception e){e.printStackTrace();}
}
private void readObject(ObjectInputStream oi){
try {
oi.defaultReadObject();
this.idade = oi.readInt();
this.peso = oi.readInt();
} catch(Exception e){e.printStackTrace();}
}
@Override
public String toString(){
return “Nome: ” + this.getNome() + ” Idade: ” + this.getIdade() + ” Peso: ” + this.getPeso();
}
}
Output:
Nome: Pedro Idade: 34 Peso: 88
Nome: Pedro Idade: 34 Peso: 88
Vamos fazer algumas observações:
-
A ordem em que as coisas ocorrem no método writeObject e readObject na classe Dog tem que ser exatamente igual. Se invertemos por exemplo:
private void writeObject(ObjectOutputStream os){
try { os.writeInt(this.idade); os.defaultWriteObject(); os.writeInt(this.peso); } catch(Exception e){e.printStackTrace();} } |
private void readObject(ObjectInputStream oi){
try { oi.defaultReadObject(); this.idade = oi.readInt(); this.peso = oi.readInt(); } catch(Exception e){e.printStackTrace();} } |
Teremos o seguinte erro em tempo de compilação:
java.io.StreamCorruptedException: unexpected block data
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1361)
private void writeObject(ObjectOutputStream os){
try { os.defaultWriteObject(); os.writeInt(this.peso); os.writeInt(this.idade); } catch(Exception e){e.printStackTrace();} } |
private void readObject(ObjectInputStream oi){
try { oi.defaultReadObject(); this.idade = oi.readInt(); this.peso = oi.readInt(); } catch(Exception e){e.printStackTrace();} } |
Teremos o seguinte resultado (também invertido)
Nome: Pedro Idade: 34 Peso: 88
Nome: Pedro Idade: 88 Peso: 34
-
Outro detalhe importante é que os métodos
os.defaultWriteObject();
oi.defaultReadObject();
fazem com que a serialização e deserialização (respectivamente) dos membros não transientes ocorram normalmente
private void writeObject(ObjectOutputStream os){
try { //os.defaultWriteObject(); os.writeInt(this.peso); os.writeInt(this.idade); } catch(Exception e){e.printStackTrace();} } |
private void readObject(ObjectInputStream oi){
try { //oi.defaultReadObject(); this.idade = oi.readInt(); this.peso = oi.readInt(); } catch(Exception e){e.printStackTrace();} } |
Teremos o seguinte resultado:
Nome: Pedro Idade: 34 Peso: 88
Nome: null Idade: 88 Peso: 34
Veja que a serialização do membro nome não ocorreu.