First thing you should do is ensure that your entity is implementing the Serializable interface of the java.io package.Serializable;
After that, you will set the values of your object and with it ready you will do the actual serialization, transforming it into a set of bytes.
This is an example of a Client class, being persisted and obtained:
import java.io.Serializable;
//A classe deve implementar Serializable
public class Cliente implements Serializable {
private String nome;
private char sexo;
private String cpf;
public Cliente(String nome, char sexo, String cpf) {
super();
this.nome = nome;
this.sexo = sexo;
this.cpf = cpf;
}
public String getCpf() {
return cpf;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public char getSexo() {
return sexo;
}
public void setSexo(char sexo) {
this.sexo = sexo;
}
public String toString() {
return this.nome + " / " + "Sexo: " + this.sexo + "\n" + "CPF: "
+ this.cpf;
}
}
Below follows the main which will perform the writing and reading of objects in a file.
public class ExemploStream {
public static void main(String[] args) {
// Cria o objeto serializado
Cliente cliente = new Cliente("Glaucio Guerra", 'M', "0000000001");
try {
//Gera o arquivo para armazenar o objeto
FileOutputStream arquivoGrav =
new FileOutputStream("/Users/glaucio/Desktop/saida.dat");
//Classe responsavel por inserir os objetos
ObjectOutputStream objGravar = new ObjectOutputStream(arquivoGrav);
//Grava o objeto cliente no arquivo
objGravar.writeObject(cliente);
objGravar.flush();
objGravar.close();
arquivoGrav.flush();
arquivoGrav.close();
System.out.println("Objeto gravado com sucesso!");
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Recuperando objeto: ");
try {
//Carrega o arquivo
FileInputStream arquivoLeitura = new FileInputStreamc:/saida.dat ");
//Classe responsavel por recuperar os objetos do arquivo
ObjectInputStream objLeitura =
new ObjectInputStream(arquivoLeitura);
System.out.println(objLeitura.readObject());
objLeitura.close();
arquivoLeitura.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Exit:
Successfully recorded object!
Retrieving object:
Glaucio Guerra / Sex: M
CPF: 0000000001