【发布时间】:2017-05-27 14:05:36
【问题描述】:
我在这里尝试做的是从 MySQL 数据库中读取一些数据并将它们转换为对象数据并将其序列化到文件中。显然,确实如此。但是我在控制台中得到一个空值,我无法理解它来自哪里。如果我检查错误本身,它会在这一行显示:
pepi = (personita) ois.readObject();
你得到的输出是:
Betty, Laferez, 87.0
Manolo,Lopez,45.0
Manuel, Rodriguez, 12.0
Patricia, Alonso, 12.0
空
那么,你能帮我理解为什么这条线会导致 null 问题吗?
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());
}
}
}
【问题讨论】: