2017-05-27 72 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

相關問題