在此之前有介紹過FileStream DataStream 跟 ObjectStream的基本差別
而需要輸出輸入完整的物件類別,則需要用到ObjectStream,且必須實作序列化
並且輸入時需解虛列化。
package iotest;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.Serializable;
public class ObjectOutputStream {
public static void main(String[] args) {
// TODO Auto-generated method stub
studentGrade stu1 = new studentGrade(80,80,80);
try {
ObjectOutputStream oout = new ObjectOutputStream(new FileOutputStream("./newfolder/student.dat"));
oout.writeObject(stu1);
oout.flush();
oout.close();
System.out.println("OK1");
// FileOutputStream fout = new FileOutputStream("./newfolder/ObjectOutput");
} catch (FileNotFoundException e) {
System.out.println("Ex2");
}
try {
ObjectInputStream oin = new ObjectInputStream(new FileInputStream("./newfolder/student.dat"));
studentGrade stu2 = (studentGrade)oin.readObject(); //解序列化
System.out.println(stu2.chinese);
System.out.println(stu2.english);
System.out.println(stu2.math);
//System.out.println(s4.getAvg());
oin.close();
System.out.println("OK2");
} catch (Exception e) {
System.out.println("Ex2");
}
}
}
class studentGrade implements Serializable{ //如果沒實作序列化則不行使用ObjectIO類別輸出
int chinese,math,english;
transient int creature; //可特別將此屬性不序列化
studentGrade(int a,int b,int c){
chinese = a; math =b ; english =c;
}
}
@copyright MRcodingRoom
觀看更多文章請點MRcoding筆記
觀看更多文章請點MRcoding筆記