对象序列化方法就在这里......
public static void addNewFootBallClubToPremierLeague() throws SQLException, ClassNotFoundException, IOException{
DatabaseConnection.getConnection();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
FootBallClub.createFootBallClub();
oos.writeObject(FootBallClub.fbc);
int hashCode=FootBallClub.getNewFootBallClubName().hashCode();
byte[] footBallClubAsBytes = baos.toByteArray();
PreparedStatement pstmt = DatabaseConnection.conn.prepareStatement("INSERT INTO PremierLeague VALUES(?,?)");
ByteArrayInputStream bais = new ByteArrayInputStream(footBallClubAsBytes);
pstmt.setInt(1, hashCode);
pstmt.setBlob(2, bais);
pstmt.executeUpdate();
DatabaseConnection.conn.close();
}
对象Desirializing方法在这里.......
public static void statisticsOfSelectedPremierLeagueFootBallClubs() throws SQLException, ClassNotFoundException, IOException{
DatabaseConnection.getConnection();
DatabaseConnection.st1=DatabaseConnection.conn.createStatement();
ResultSet rs = DatabaseConnection.st1.executeQuery("SELECT name FROM PremierLeague");
FootBallClub fbc =null;
while (rs.next()) {
byte[] bArr = (byte[]) rs.getObject(1);
ByteArrayInputStream baip = new ByteArrayInputStream(bArr);
ObjectInputStream ois = new ObjectInputStream(baip);
fbc = (FootBallClub) ois.readObject();
System.out.println(fbc);
}
DatabaseConnection.st.close();
rs.close();
DatabaseConnection.conn.close();
}
当我执行第二个方法时,所有对象都为null,但是当我在第二个方法中打印对象输入流对象时,这样::::
System.out.println(ois);
此声明的输出不是空的。
为什么?
答案 0 :(得分:0)
ois
不为null,因为构造函数永远不会返回null。它们要么返回该类的新实例,要么抛出异常。
ObjectInputStream ois = new ObjectInputStream(baip);
这将为该实例创建ObjectInputStream
和ois
点的新实例。您的ois.readObject()
可能为null,否则会引发异常。
另一个重要的事情是,永远不要将序列化的流存储在数据库中,因为如果您更改了类的结构,如添加方法或变量,则序列化的对象可能无法正确反序列化。