*****探讨:怎样将存储在数据库中的二进制数据还原成自定义的java类实例?******
现在有以二进制流存储在postgresql中的自定义java类Test的实例ts,现欲将其取出,并将二进制流还原成类实例ts,部分取数的代码如下:
/*
* 从数据库中取得实例对象
* str是sql语句
*/
public void getBLOB(String str)
{
int leng=0;
int i=0;
int oid=0;
try{
conn.setAutoCommit(false);
// 获取大对象管理器以便进行操作
LargeObjectManager lobj = ((org.postgresql.PGConnection)conn).getLargeObjectAPI();
ResultSet rs=exeQuery(str);
conn.commit();
while (rs.next())
{
oid=rs.getInt(1);
//取得数据库中的大对象
LargeObject obj=lobj.open(oid,LargeObjectManager.READ);
byte buf[] = new byte[obj.size()];
//将obj中的二进制字节读入buf
obj.read(buf, 0, obj.size());
FileOutputStream fos = new FileOutputStream("test1.data");
ObjectOutputStream op= new ObjectOutputStream(fos);
//将buf写入输出流
op.write(buf);
op.flush();
op.close();
FileInputStream fis =new FileInputStream("test1.data");
ObjectInputStream in=new ObjectInputStream(fis);
//从流中读出实例对象s
SampleTest s = (SampleTest)in.readObject();
obj.close();
in.close();
fos.close();
fis.close();
}
conn.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
其中:
//从流中读出实例对象s
SampleTest s = (SampleTest)in.readObject();
出现异常:
java.io.OptionalDataException
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1285)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:324)
请各位指教,出现异常的原因是什么?或者说怎样才能将数据库中的二进制流读出来还原成类的实例?