2017-05-27 76 views
0

我在这里要做的是从MySQL数据库中读取一些数据,并将它们转换为对象数据并将其序列化为一个文件。显然,它的确如此。但是我在控制台中得到一个null,我无法理解它来自哪里。如果我检查错误本身,它说,它在这条线:为什么在使用ResultSet时会得到一个额外的null结果?

pepi = (personita) ois.readObject(); 

你得到的输出是:

贝蒂,Laferez,87.0 < - 从数据库,OK。

Manolo,Lopez,45.0 < - 从数据库中,确定。

Manuel,Rodriguez,12.0 < - 从数据库中,确定。

Patricia,Alonso,12.0 < - 从数据库中,确定。

null < - ???

那么,你能帮我理解为什么这行代码导致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()); 
    } 

} 

}

回答

0

编辑2 - 我改变了我的答案

阅读本Question

你的代码是正确后。 您得到的null是EOFException catch中的e.getMessage(),您可以简单地通过用';'替换System.println语句来避免)。

}catch(EOFException e){ 
    ; 
} 

反对什么,我还以为你不看在steram的内空值,所以要知道,当你达到你使用这个EOFException类流的结束。在我提到的问题中,有一点需要考虑,因为掌握EOF的原因是因为没有更多的对象需要阅读,或者因为错误和流被关闭了。

+0

是否像你说的那样;完全相同的错误。 –

+0

编辑完成后,我仍然收到null。 –

+0

你可以替换System.out.println(e.getMessage());通过e.printStackTrace();并告诉我它是否打印出不同的东西? – Juan

相关问题