我在从数据库中正确检索我自己的类“BallotPaper”的特定对象时遇到问题。它可以正确保存,但在创建 ObjectInputStream 时会引发异常。
当然,我在这里阅读了许多类似的问题和答案,但仍然无法处理。
在数据库中,我有一个包含 bytea 类型列(它是 postgreSQL)的表,我在其中保存我的对象。
下面是几行代码:
//Saving the object 'paper' of the class 'BallotPaper'
PreparedStatement st = connection.prepareStatement(query);
ByteArrayOutputStream byos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(byos);
oos.writeObject(paper);
byte[] bytePaper = byos.toByteArray();
st.setBytes(1, bytePaper);
st.executeUpdate();
byos.close();
oos.close();
st.close();
//Trying to retrieve the object:
String query2 = "SELECT paper FROM voters WHERE id="+_id+";";
Statement s = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
ResultSet r = s.executeQuery(query2);
r.first();
bytePaper = r.getBytes(1);
ByteArrayInputStream b = new ByteArrayInputStream(bytePaper);
ObjectInputStream o = new ObjectInputStream(b); // *
BallotPaper ba = (BallotPaper)o.readObject();
异常在最后一行抛出,标有 * 。
它看起来像这样:
java.io.StreamCorruptedException: invalid stream header: BB656430
at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
at java.io.ObjectInputStream.<init>(Unknown Source)
at slave.VotersDB.saveFilledPaper(VotersDB.java:162)
at slave.ClientThread.prepareResponse(ClientThread.java:50)
at slave.ClientThread.run(ClientThread.java:72)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
感谢您的所有回答。