java学习

来源:互联网 发布:水果合成软件下载 编辑:程序博客网 时间:2024/06/03 16:22
package po2;
import java.io.*;
public class Ioexercise2 {
   public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
       //准备数据
    Student[] stuArray = new Student[]{new Student(1,"A",18,1),new Student(2,"B",19,2),new Student(3,"C",20,3)};  
       String fileName="myfile.txt"; //代表本工程根目录下的文件
       //序列化——写出对象
       for(int i=0;i<stuArray.length;i++)
       {
        writeStuObject(fileName,stuArray[i]);
        Student stuArray1=(Student)readStuObject(fileName);
       System.out.println(stuArray1);
       }
    }
 
    private static Student readStuObject(String fileName) throws FileNotFoundException, IOException, ClassNotFoundException {
       ObjectInputStream ois=new ObjectInputStream(new FileInputStream(fileName));
       Student stuArray1=(Student)ois.readObject();
       ois.close();
       return stuArray1;
    }
 
    private static void writeStuObject(String fileName, Student stuArray) throws FileNotFoundException, IOException {
       ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream(fileName));
       oos.writeObject(stuArray);
       oos.close();
       
    }


   }