本文分兩段,上端自己寫的,下端網上別人寫的
public class SerializableTest1
{
/**
* 保存爲一個二進制的文件
*/
public static void main(String[] args) throws Exception
{
Person p1 = new Person(20,"張三",33.4);
Person p2 = new Person(50,"李四",53.4);
Person p3 = new Person(10,"王五",123.4);
//存入序列化的對象
FileOutputStream fos = new FileOutputStream("person.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(p1);
oos.writeObject(p2);
oos.writeObject(p3);
oos.close();
///////////////////////////////////////////////////////
//取出序列化的對象
FileInputStream fn = new FileInputStream("person.txt");
ObjectInputStream ois = new ObjectInputStream(fn);
while(fn.available() > 0) //代表文件中還有內容
{
Person p = (Person)ois.readObject();
System.out.println(p);
}
}
}
class Person implements Serializable
{
String name;
int age;
// transient int age; //此屬性不可序列化
double height;
public Person(int age, String name, double height)
{
this.age = age;
this.name = name;
this.height = height;
}
public String toString()
{
return this.name + "," +this.age + "," + this.height;
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////
爲尊重原創作者,貼出原始地址:
http://www.cnblogs.com/liaoweipeng/p/4474680.html
這幾天做一個小的聊天項目用到對象序列化的知識,發現對象序列化不能像普通文件一樣直接追加對象。每次寫入對象都會被覆蓋。弄了2個多小時終於解決了。Java默 認的對象序列化是每次寫入對象都會寫入一點頭aced 0005(佔4個字節),然後每次讀取都讀完頭然後在讀內容。解決方法就是先判斷文件是否存在。如果不存在,就先創建文件。然後寫了第一個對象,也寫入了 頭aced 0005。追加的情況就是當判斷文件存在時,把那個4個字節的頭aced 0005截取掉,然後在把對象寫入到文件。這樣就實現了對象序列化的追加。代碼如下。
String filename=m.getGetter()+m.getSender();
File file=
new
File(
"D:\\"
+filename+
".txt"
);
if
(file.exists()){
isexist=
true
;
FileOutputStream fo=
new
FileOutputStream(file,
true
);
ObjectOutputStream oos =
new
ObjectOutputStream(fo);
long
pos=
0
;
if
(isexist){
pos=fo.getChannel().position()-
4
;
fo.getChannel().truncate(pos);
}
oos.writeObject(m);
//進行序列化
}
else
{
//文件不存在
file.createNewFile();
FileOutputStream fo=
new
FileOutputStream(file);
ObjectOutputStream oos =
new
ObjectOutputStream(fo);
oos.writeObject(m);
//進行序列化
}
下面是系列化的實現。注意要在循環外面關閉流,在裏面關閉會出現句柄無效的錯誤。
String fileName=owner+friendNo;
File file =
new
File(
"D:"
+File.separator+fileName+
".txt"
);
if
(file.exists()){
ObjectInputStream ois;
try
{
FileInputStream fn=
new
FileInputStream(file);
ois =
new
ObjectInputStream(fn);
while
(fn.available()>
0
){
//代表文件還有內容
Message p = (Message)ois.readObject();
//從流中讀取對象
System.out.println(p.getCon);
}
ois.close();
//注意在循環外面關閉
}
catch
(Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
------------------------------------------------------------------------------------------------
往下爲本人所寫