對象流寫出到文件的代碼
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Date;
/*
?* 對象流:
?* 1先寫出后讀取
?* 2讀取的順序和寫出保持一致
?* 3不是所有的對象都可以序列化Serializable
?*/
public class ObjectTest3 {
?? ?public static void main(String[] args) throws IOException, ClassNotFoundException {
?? ??? ?
?? ??? ?ObjectOutputStream oos=
?? ??? ??? ??? ?new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream("obj.ser")));
?? ??? ?oos.writeUTF("我太難了");
?? ??? ?oos.writeInt(18);
?? ??? ?oos.writeBoolean(false);
?? ??? ?//加入對象
?? ??? ?oos.writeObject("希望世界和平");
?? ??? ?oos.writeObject(new Date());
?? ??? ?Employee emp=new Employee("小二",400);
?? ??? ?oos.writeObject(emp);
?? ??? ?oos.flush();
?? ??? ?oos.close();
?? ??? ? ?
?? ??? ?ObjectInputStream ois=
?? ??? ??? ??? ?new ObjectInputStream(new BufferedInputStream(new FileInputStream("obj.ser")));
?? ??? ? String msg=ois.readUTF();
?? ??? ? int age=ois.readInt();
?? ??? ? boolean flag=ois.readBoolean();
?? ??? ? Object str=ois.readObject();
?? ??? ? Object date=ois.readObject();
?? ??? ? Object employee=ois.readObject();
?? ??? ? //接下來我們就將類型還原,這里我們必須加上類型轉(zhuǎn)換
?? ??? ? if(str instanceof String) {
?? ??? ??? ? String strObj=(String)str;
//?? ??? ??? ? System.out.println(strObj);
?? ??? ? }
?? ??? ? if(date instanceof Date) {
?? ??? ??? ? Date dateObj=(Date)date;
//?? ??? ??? ? System.out.println(dateObj);
?? ??? ? }
?? ??? ? if(employee instanceof Employee) {
?? ??? ??? ?Employee empObj=(Employee)employee;
?? ??? ??? ? System.out.println(empObj.getName()+"-->"+empObj.getSalary());
?? ??? ? }
//?? ??? ? System.out.println(msg);
?? ??? ? ois.close();
?? ??? ?
?? ??? ?
?? ??? ?
?? ??? ?
?? ?}
}
標(biāo)簽: