What I'm trying to do here, is to read some data from a MySQL database and the convert them into object data and serialize it in a file. Which apparently, it does. But I get a null in the console that I'm not able to understand where does it come from. If I check the error itself, it says it on this line:
pepi = (personita) ois.readObject();
The output you get is:
Betty, Laferez, 87.0 <- From database, ok.
Manolo, Lopez, 45.0 <- From database, ok.
Manuel, Rodriguez, 12.0 <- From database, ok.
Patricia, Alonso, 12.0 <- From database, ok.
null <- ???
So, could you can help me understanding why this line is causing the null problem?
public class practicabdyserializableobjetos {
public static void main(String[] args) throws ClassNotFoundException, IOException {
Class.forName("com.mysql.jdbc.Driver");
Connection conexion = null;
try {
conexion = DriverManager.getConnection("jdbc:mysql://localhost/programacion", "root", "password");
Statement sentencia = (Statement) conexion.createStatement();
ResultSet resultado = sentencia.executeQuery("Select * from ejemplo");
File persofiles = new File("./persofiles.txt");
if (!persofiles.exists())
persofiles.createNewFile();
FileOutputStream fioust = new FileOutputStream(persofiles);
ObjectOutputStream oboust = new ObjectOutputStream(fioust);
int p=0;
while (resultado.next()) {
personita per = new personita();
per.setNombre(resultado.getString(1));
per.setApellido(resultado.getString(2));
per.setEdad(resultado.getDouble(3));
oboust.writeObject(per);
}
oboust.close();
fioust.close();
FileInputStream fis = new FileInputStream(persofiles);
@SuppressWarnings("resource")
ObjectInputStream ois = new ObjectInputStream(fis);
while (true) {
personita pepi = new personita();
pepi = (personita) ois.readObject();
System.out.println(pepi.getNombre() + ", " + pepi.getApellido() + ", " + pepi.getEdad());
}
} catch (SQLException e) {
e.printStackTrace();
}
catch(EOFException e){
System.out.println(e.getMessage());
}
}
}