您好我遇到序列化对象的问题。我真正想要做的是从服务器获取记录使用hashmap序列化它并将其保存在sqllite db中。
我可以将序列化的对象保存到我的存储卡中,但是当我反序列化时,nohting就会出现,我以前的所有数据都会被删除。
以下是序列化的示例代码
序列化
Employee e = new Employee();
e.name = "Reyan Ali";
e.address = "Phokka Kuan, Ambehta Peer";
e.SSN = 11122333;
e.number = 101;
try
{
FileOutputStream fileOut =
new FileOutputStream("/tmp/employee.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut.close();
System.out.printf("Serialized data is saved in /tmp/employee.ser");
}catch(IOException i)
{
i.printStackTrace();
}
}
反序列化
Employee e = null;
try
{
FileInputStream fileIn = new FileInputStream("/tmp/employee.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
e = (Employee) in.readObject();
in.close();
fileIn.close();
}catch(IOException i)
{
i.printStackTrace();
return;
}catch(ClassNotFoundException c)
{
System.out.println("Employee class not found");
c.printStackTrace();
return;
}
System.out.println("Deserialized Employee...");
System.out.println("Name: " + e.name);
System.out.println("Address: " + e.address);
System.out.println("SSN: " + e.SSN);
System.out.println("Number: " + e.number);
}
其次,sqlite中可以保存序列化对象的列类型是什么。 如果你们有人有一个很好的教程请分享。
答案 0 :(得分:1)
对您的代码进行了一些更改,如下所示。
首先在Employee.java类中实现Serializable接口
public void serailize() {
Employee e = new Employee();
e.setName("Reyan Ali");
e.setAddress("Phokka Kuan, Ambehta Peer");
e.setSSN(11122333);
e.setNumber(101);
try {
ObjectOutputStream out = new ObjectOutputStream(openFileOutput(
"employee.ser", MODE_PRIVATE));
out.writeObject(e);
out.close();
System.out.printf("Serialized data is saved in /tmp/employee.ser");
} catch (IOException i) {
i.printStackTrace();
}
}
public void deSerailize() {
Employee e = null;
try {
ObjectInputStream in = new ObjectInputStream(
openFileInput("employee.ser"));
e = (Employee) in.readObject();
in.close();
} catch (IOException i) {
i.printStackTrace();
return;
} catch (ClassNotFoundException c) {
System.out.println("Serialized class not found");
c.printStackTrace();
return;
}
System.out.println("Deserialized Employee...");
System.out.println("Name: " + e.name);
System.out.println("Address: " + e.address);
System.out.println("SSN: " + e.SSN);
System.out.println("Number: " + e.number);
}
OpenFileInput()和openFileOutPut()是应用程序专用文件。
我认为将序列化数据存储在文件中是很好的。