public class SerialTest{
private static Connection conn=null;
private static PreparedStatement ps=null;
private static ResultSet rs=null;
public void serialize(){
User user=new User(“1000″,”zhuchaofan”,”123″);
conn=jdbcUtil.getConnection();
String sql=”insert into user_info values(?)”;
try {
ps=conn.prepareStatement(sql);
// ps.setObject(1, user);
ps.setBytes(1,SerializeUtil.serializeObject(user));
ps.execute();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
jdbcUtil.CloseAll(ps, rs, conn);
}
}
public void deserialize(){
conn=jdbcUtil.getConnection();
String sql=”select * from user_info”;
User user=new User();
try {
ps=conn.prepareStatement(sql);
rs=ps.executeQuery();
while(rs.next()){
byte[] bytes=rs.getBytes(“data”);
user=(User)SerializeUtil.deserializeObject(bytes);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
jdbcUtil.CloseAll(ps, rs, conn);
}
}
public static void main(String[] args) {
SerialTest rt=new SerialTest();
// rt.serialize();
rt.deserialize();
}
}
===================================================================序列化和反序列化
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public final class SerializeUtil {
/** 序列化对象
* @throws IOException */
public static byte[] serializeObject(Object object) throws IOException{
ByteArrayOutputStream saos=new ByteArrayOutputStream();
ObjectOutputStream oos=new ObjectOutputStream(saos);
oos.writeObject(object);
oos.flush();
return saos.toByteArray();
}
/** 反序列化对象
* @throws IOException
* @throws ClassNotFoundException */
public static Object deserializeObject(byte[]buf) throws IOException, ClassNotFoundException{
Object object=null;
ByteArrayInputStream sais=new ByteArrayInputStream(buf);
ObjectInputStream ois = new ObjectInputStream(sais);
object=ois.readObject();
return object;
}
}
=======================================错误==================================
java.io.StreamCorruptedException: invalid stream header: 41434544
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:804)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:299)
at com.guigu.test.SerializeUtil.deserializeObject(SerializeUtil.java:29)
at com.guigu.test.SerialTest.deserialize(SerialTest.java:46)
at com.guigu.test.SerialTest.main(SerialTest.java:69)
问:
反序列化的ObjectInputStream ois = new ObjectInputStream(sais);这里出了问题,
错误显示时invalid stream header:41434544
本人参考了一些网上的例子,感觉没有什么差别,不知道为什么程序到本人这里就会报这个错误。
本人猜测是原因是
byte[] bytes=rs.getBytes(“data”);
user=(User)SerializeUtil.deserializeObject(bytes);
这里传递的参数是纯粹的数组。能否需要放到流对象里面再拿出来
20
20