为什么在使用 ResultSet 时会得到一个额外的 null 结果?

Why do I get one extra result with null when using ResultSet?

我在这里要做的是从 MySQL 数据库中读取一些数据并将它们转换为对象数据并将其序列化到一个文件中。显然,它确实如此。但是我在控制台中得到一个空值,我无法理解它来自哪里。如果我自己检查错误,它会在这一行显示:

pepi = (personita) ois.readObject();

你得到的输出是:

Betty, Laferez, 87.0 <- 来自数据库,好的。

马诺洛,洛佩兹,45.0 <- 来自数据库,好的。

Manuel, Rodriguez, 12.0 <- 来自数据库,好的。

帕特里夏,阿隆索,12.0 <- 来自数据库,好的。

<- ???

那么,你能帮我理解为什么这一行会导致空问题吗?

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());
    }

}

}

编辑 2 - 我更改了答案

看完这篇Question

您的代码是正确的。 您得到的 null 是 EOFException 捕获中的 e.getMessage() ,您可以通过将 System.println 语句替换为 ';').

来简单地避免这种情况
}catch(EOFException e){
   ;
}

与我的想法相反,您没有在 steram 的末尾读取空值,因此要知道您何时到达流的末尾,您可以使用此 EOFException。在我提到的问题中,有一个考虑因素,因为您可以知道 EOF 加注是因为没有更多对象可读,还是因为出现错误并且流已关闭。