//先写出一个Student类方便new对象 ,重写toString方法方便输出;
public class Student implements Serializable{
//这里要实现Serializable接口,这是标记接口,类似 colenable接口;告诉程序该对象可被序列化;
private static final long serialVersionUID = 1L;
//ID用途可以在修改对象的属性的时候另一边输出不会报错,增加或者修改的参数会默认为初始值;
private String name;
private int num;
public Student(String name, int num) {
super();
this.name = name;
this.num = num;
}
@Override
public String toString() {
return "Student [name=" + name + ", num=" + num + "]";
}
}
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class TestObject {
static String []s = {"自动","都是","大方","感受到"};
static String s1 = "sfsfsgfsgsgs";
static Student s2 = new Student("李上",22);
static Student s3 = new Student("发的",22);
static Student s4 = new Student("风扇",22);
static Student s5 = new Student("df",22);
//new出对象,也可以直接把对象挨个写入文件中,再挨个读出来;
//当用while读取多个对象时候要用到while(Objiet!=null) {}
//程序会在读取到最后一个的时候继续读取下一个,然后报错,预防的方法是
//在写入时候最后写入一个null对象,当读取到null时候程序就会跳出循环;
public static void main(String[] args) {
TestObject t =new TestObject();
t.testw();
t.testr();
}
public void testw() {
File f = new File("G:\\demo\\x.txt");
List<Student> ls = new ArrayList<>();
ls.add(s2);
ls.add(s3);
ls.add(s4);
ls.add(s5);
//把对象放入集合中
ObjectOutputStream oos =null;
try {
oos = new ObjectOutputStream(new FileOutputStream(f));
oos.writeObject(ls);
//把整个集合写入文件之中;
System.out.println();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
oos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void testr() {
File f = new File("G:\\demo\\x.txt");
ObjectInputStream ois =null;
try {
ois = new ObjectInputStream(new FileInputStream(f));
List<Student> ls= (List<Student>) ois.readObject();
//读取时候要注意输出对象的类型,放入什么类型就要用什么类型来接收;
System.out.println(ls);
//打印时候也要注意对象类型的转化;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//最后要注意在使用完流之后要使用close();方法关闭;