定义一个Student类,里面含name、age属性;
定义一个测试类,创建一个Student数组,数组中的Student对象赋初值,将数组中的各个Student对象的内容输出到student.txt文件中;
然后将文件中的内容读出并在显示器中显示出来。
package test1;
import java.io.*;
import java.util.*;
public class Main {
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
Student s1 = new Student("Tom", 18);
Student s2 = new Student();
File file = new File("D:\\student.txt");
try
{
FileOutputStream out = new FileOutputStream(file);
ObjectOutputStream oout = new ObjectOutputStream(out);
oout.writeObject(s1);
oout.close();
out.close();
FileInputStream in = new FileInputStream(file);
ObjectInputStream oin = new ObjectInputStream(in);
s2 = (Student) oin.readObject();
System.out.println(s2.toString());
oin.close();
in.close();
}catch (Exception e)
{
e.printStackTrace();
}