I have to send a serialized Java object, I already have this method that receives an object and sends, my question is how to set the values in the object, my data is in the database, submit? I've never done that, so I have this doubt.
I have to send a serialized Java object, I already have this method that receives an object and sends, my question is how to set the values in the object, my data is in the database, submit? I've never done that, so I have this doubt.
First thing you should do is make sure your entity is implementing the Serializable interface of the java.io.Serializable package;
After this, you will set the values of your object and with it 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 is the main that will perform the recording 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();
}
}
}
Output:
Object saved successfully!
Retrieving object:
Glaucio Guerra / Sex: M
CPF: 0000000001