能直接运行的:
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.io.*;
import javax.naming.BinaryRefAddr;
public class Student implements Serializable{//Serializable是申明这个类可以被序列化
/**
* @param args
*/
public static void main(String[] args) {
ArrayList <Student> ss=new ArrayList<Student>();
for(int i=0;i<5;i++)//初始化5个学生
{
Student s=new Student(i,"学生"+i);
s.chenese_score=i+50;
s.english_score=i+75;
s.math_score=i+80;
ss.add(s);
}
try {
FileOutputStream fos=new FileOutputStream("d:/STUDENT.DAT");
try {
ObjectOutputStream oos=new ObjectOutputStream(fos);
for(int i=0;i<ss.size();i++)//初始化5个学生
{
Student s=ss.get(i);
oos.writeObject(s);//将学生遍历出来写入文件中
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//从文件中读取一个学生出来出来
try {
FileInputStream fis=new FileInputStream("d:/STUDENT.DAT");
try {
ObjectInputStream ois=new ObjectInputStream(fis);
try {
Student s=(Student)ois.readObject();
System.out.println("学生名为 "+s.name+"的总分为:"+s.getAll_score());
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public int id;
public String name;
public int chenese_score;
public int math_score;
public int english_score;
public int all_score;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
public int getAll_score()//获取总成绩
{
return this.chenese_score+this.english_score+this.math_score;
}
}
温馨提示:答案为网友推荐,仅供参考