对象流的读入与写出的简单应用
需要注意的事情:
1.用对象流写的对象必须要实现Serializable接口----贴标签技术
2.对象流的读取必须采用捕捉异常的方式控制结束,不能采用available()>0
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import org.junit.Test;
public class ObjectStrean {
@Test
public void testObjWrite() {
ObjectOutputStream out = null;
try {
// 后序可以随便
out = new ObjectOutputStream(new FileOutputStream("E:/test/person.ppp"));
for (int i = 0; i < 5; i++) {
Person person = new Person("nn" + i, 10 + i);
out.writeObject(person);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@Test
public void testIn() {
ObjectInputStream in = null;
try {
in = new ObjectInputStream(new FileInputStream("E:/test/person.ppp"));
// while(in.available()>0){//读取对象流不能使用available
while (true) {
Person person = (Person) in.readObject();
System.out.println(person);
}
} catch (EOFException e) {
System.out.println("Over!");
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
// 对象流的读取对象必须实现序列化接口
class Person implements Serializable {
private static final long serialVersionUID = 1L;
String name;
int age;
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public Person() {
super();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return name + "," + age;
}
}