注意事项:.对象需要连接可序列化对象: Serialzable。 代码如下:
package com.owant;
import java.io.Serializable;
public class MyObject implements Serializable {
private String name; // 名字
private String title;// 头衔
private String email;// 邮件
private int tel; // 电话
private String info; // 信息
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getTel() {
return tel;
}
public void setTel(int tel) {
this.tel = tel;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
}
对象序列化:
package com.owant;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class ObjectToStream {
/**
*对象序列化:
* 将对象转化为二进制的文字
*
*/
public static void main(String[] args) {
try {
FileOutputStream outputStream=new FileOutputStream("F:/db/object.dat");
//创建一个对象
MyObject object=new MyObject();
object.setName("钟刘旺");
object.setTitle("欣赏创造美好未来");
object.setTel(1360800712);
object.setEmail("owant.@139.com");
object.setInfo("今天,我在研究对象序列化的问题。");
ObjectOutputStream oos=new ObjectOutputStream(outputStream);
oos.writeObject(object);
oos.close();
outputStream.close();
System.out.println("写入成功!");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
对象反序列化:
package com.owant;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
public class ObjectFormStream {
/**
* 反序列化:
* 将二进制的对象转化为对象
*
*/
public static void main(String[] args) {
try {
FileInputStream inputStream=new FileInputStream("F:/db/object.dat");
ObjectInputStream ois=new ObjectInputStream(inputStream);
MyObject object=(MyObject)ois.readObject();
ois.close();
inputStream.close();
System.out.println("读取到的对象是:\n"+
"name:"+object.getName()+"\n"+
"title:"+object.getTitle()+"\n"+
"tel:"+object.getTel()+"\n"+
"email:"+object.getEmail()+"\n"+
"info:"+object.getInfo()
);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
System.out.println("没找到这个对象!");
e.printStackTrace();
}
}
}