Last active
August 29, 2015 14:01
-
-
Save werbet/6ec4281e5326411efc32 to your computer and use it in GitHub Desktop.
Simple java serialization example depicting the serialization of multiple objects into a single file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.FileInputStream; | |
import java.io.FileOutputStream; | |
import java.io.ObjectInputStream; | |
import java.io.ObjectOutputStream; | |
import java.io.Serializable; | |
public class Serialization | |
{ | |
public static void main(String args[]) throws Exception | |
{ | |
ObjectOutputStream saida = null; | |
String nomeArquivo = "arquivo.binario"; | |
saida = new ObjectOutputStream(new FileOutputStream(nomeArquivo,true)); | |
ClasseExemplo aux = new ClasseExemplo(); | |
aux.setar(100,"Eriko"); | |
gravar(saida, aux); | |
aux.setar(200,"Othon"); | |
gravar(saida, aux); | |
aux.setar(300,"Luana"); | |
gravar(saida, aux); | |
saida.close(); | |
} | |
private static void gravar(ObjectOutputStream out, ClasseExemplo dados) throws Exception | |
{ | |
dados.imprimir(); | |
out.writeObject(dados); | |
out.reset(); | |
} | |
} | |
class ClasseExemplo implements Serializable | |
{ | |
private static final long serialVersionUID = 1L; | |
private String nome; | |
private int id; | |
void setar(int id, String nome) | |
{ | |
this.id = id; | |
this.nome = nome; | |
} | |
void imprimir() | |
{ | |
System.out.println("ID = " + id); | |
System.out.println("Nome = " + nome); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment