Object对象流
package liuer; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class Student implements java.io.Serializable{ private String name; private Date birth; private int score; private static SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); public Student(String name, String birth, int score) throws ParseException { super(); this.name = name; this.birth = sdf.parse(birth); this.score = score; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getBirth() { return birth; } public void setBirth(Date birth) { this.birth = birth; } public int getScore() { return score; } public void setScore(int score) { this.score = score; } @Override public String toString() { return "Student [name=" + name + ", birth=" + birth + ", score=" + score + "]"; } }
package liuer; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.text.ParseException; import java.util.ArrayList; import java.util.List; public class Testwrite { public static void main(String[] args) throws FileNotFoundException, IOException, ParseException, ClassNotFoundException { write(); read(); } //写数据 public static void write() throws FileNotFoundException, IOException, ParseException{ ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("d:/object.txt")); oos.writeInt(90); oos.writeInt(-89); oos.writeDouble(Math.PI); oos.writeUTF("要是能重来我要选李白"); List<Student>list=new ArrayList<Student>(); list.add(new Student("张三那","1992-12-11", 60)); list.add(new Student("张三feng","1987-12-11", 80)); oos.writeObject(list); oos.close(); } public static void read() throws FileNotFoundException, IOException, ClassNotFoundException{ ObjectInputStream ois=new ObjectInputStream(new FileInputStream("d:/object.txt")); System.out.println(ois.readInt()); System.out.println(ois.readInt()); System.out.println(ois.readDouble()); System.out.println(ois.readUTF()); List<Student> s=(List<Student>)ois.readObject(); for(Student ss:s){ System.out.println(ss); } ois.close(); } }