ObjectInputStream에서 모든 객체를 순환해서 읽는 방법
6964 단어 java-개체 흐름
package test816;
import java.io.EOFException;
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.io.Serializable;
public class OutputStreamTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
String path = "d.txt";
ObjectInputStream ois = null;
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(new FileOutputStream(path));
Person p1 = new Person(" ", 12, true);
Person p2 = new Person(" ", 33, false);
oos.writeObject(p1);
oos.writeObject(p2);
***oos.writeObject(null);***
// null , EOFException , try catch ( )
oos.flush();
System.out.println(" ");
ois = new ObjectInputStream(new FileInputStream(path));
Object object = ois.readObject();
while( object !=null){
System.out.println(object.toString());
object = ois.readObject();
}
}
// catch(EOFException e){
// System.out.println("end");
// }
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{
if(oos!= null){
try {
oos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(ois!= null){
try {
ois.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
class Person implements Serializable{
private String name ;
private int age;
private boolean sex;
private void Perosn() {
// TODO Auto-generated method stub
}
public Person(String name, int age, boolean sex) {
super();
this.name = name;
this.age = age;
this.sex = sex;
}
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;
}
public boolean isSex() {
return sex;
}
public void setSex(boolean sex) {
this.sex = sex;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + ", sex=" + (sex?" ":" ") + "]";
}
}
사용하는 클래스를 서열화하는 것을 기억하십시오. 즉, Serializable 인터페이스를 실현하는 것입니다. 이 인터페이스는java에 속합니다.io 패키지