Difference between revisions of "Entradas e Saídas em Java/Exemplo 04: Serialização de Objectos"

From Wiki**3

< Entradas e Saídas em Java
(Created page with "== Serialização de Objectos == Serialização de tipos primitivos e de objectos: a interface Serializable. Elementos não serializáveis: a palavra chave transient. === Exem...")
(No difference)

Revision as of 18:30, 4 November 2013

Serialização de Objectos

Serialização de tipos primitivos e de objectos: a interface Serializable. Elementos não serializáveis: a palavra chave transient.

Exemplo: Zorg e Zog

<java5> class Alienígena implements Serializable {

 String _nome;
 transient String _segredo = "7";
 public Alienígena(String n) { _nome = n; _segredo = _nome + _nome.length(); }
 public void voing() { System.out.println(_nome + (_segredo != null ? _segredo : "")); }

} </java5>

<java5> public class Serialização {

 public static void main(String[] args) throws IOException, ClassNotFoundException {
   Alienígena a1 = new Alienígena("Zorg"), a2 = new Alienígena("Zog");
   a1.voing();  //output: ZorgZorg4
   a2.voing();  //output: ZogZog3
   ObjectOutputStream out =
     new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream("raw.dat")));
   out.writeObject(a1); out.writeObject(a2);
   out.close();
   ObjectInputStream in =
     new ObjectInputStream(new BufferedInputStream(new FileInputStream("raw.dat")));
   Alienígena r1 = (Alienígena)in.readObject();  // pode lançar “StreamCorruptedException”
   Alienígena r2 = (Alienígena)in.readObject();
   r1.voing();  //output: Zorg
   r2.voing();  //output: Zog
 }

} </java5>