当前位置: 技术问答>java相关
能不能将对象序列化后存到数据库再取出还原?有没有例子?
来源: 互联网 发布时间:2015-02-24
本文导语: | public static byte[] bwritedato(Object data) { byte[] bx = new byte[1]; try { ObjectOutputStream fin; ByteArrayOutputStream b = new ByteArrayOutputStream(); fin = ...
|
public static byte[] bwritedato(Object data)
{
byte[] bx = new byte[1];
try
{
ObjectOutputStream fin;
ByteArrayOutputStream b = new ByteArrayOutputStream();
fin = new ObjectOutputStream(b);
fin.writeObject(data);
fin.flush();
fin.close();
fin = null;
bx = new byte[b.size()];
bx = b.toByteArray();
}
catch(Exception e)
{
log(" bAppending/writing object data error : " + e.toString());
}
return bx;
}
public static Object breaddato(byte[] data)
{
Object bx = new Object();
try
{
ObjectInputStream fin;
ByteArrayInputStream b = new ByteArrayInputStream(data);
fin = new ObjectInputStream(b);
bx = fin.readObject();
fin.close();
fin = null;
}
catch(Exception e)
{
log(" bAppending/writing object data error : " + e.toString());
}
return bx;
}
{
byte[] bx = new byte[1];
try
{
ObjectOutputStream fin;
ByteArrayOutputStream b = new ByteArrayOutputStream();
fin = new ObjectOutputStream(b);
fin.writeObject(data);
fin.flush();
fin.close();
fin = null;
bx = new byte[b.size()];
bx = b.toByteArray();
}
catch(Exception e)
{
log(" bAppending/writing object data error : " + e.toString());
}
return bx;
}
public static Object breaddato(byte[] data)
{
Object bx = new Object();
try
{
ObjectInputStream fin;
ByteArrayInputStream b = new ByteArrayInputStream(data);
fin = new ObjectInputStream(b);
bx = fin.readObject();
fin.close();
fin = null;
}
catch(Exception e)
{
log(" bAppending/writing object data error : " + e.toString());
}
return bx;
}
|
以下代码需要配合路人甲的代码
private void saveToDB(){
String sqlstr="INSERT INTO ASSESS (FILE_MODEL) VALUES (?)";
try
{
PreparedStatement pst=connect.prepareStatement(sqlstr);
pst.setBinaryStream(1,GetThisFileBlob(),GetThisFileBlob().available());
} catch(Exception ex){
}
}
private FileInputStream GetThisFileBlob(String strFileName){
// 将刚才保存的文件作为流输入
}
private String saveFileToLocal(OutputStream out) {
// 将存有序列化对象的流存入文件
}
private void saveToDB(){
String sqlstr="INSERT INTO ASSESS (FILE_MODEL) VALUES (?)";
try
{
PreparedStatement pst=connect.prepareStatement(sqlstr);
pst.setBinaryStream(1,GetThisFileBlob(),GetThisFileBlob().available());
} catch(Exception ex){
}
}
private FileInputStream GetThisFileBlob(String strFileName){
// 将刚才保存的文件作为流输入
}
private String saveFileToLocal(OutputStream out) {
// 将存有序列化对象的流存入文件
}