Skip to content

Instantly share code, notes, and snippets.

@werbet
Last active August 29, 2015 14:01
Show Gist options
  • Save werbet/6ec4281e5326411efc32 to your computer and use it in GitHub Desktop.
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
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