62,615
社区成员
发帖
与我相关
我的任务
分享
package com.donghe.package1;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
public class ObjectIntputStreamDemo {
public static void main(String[] args){
ObjectInputStream ois =null;
try {
ois = new ObjectInputStream(new FileInputStream("e:\\person.tmp") );
Object ob = ois.readObject();
System.out.println(ois.read());
if (ob!= null){
Person p= (Person)ob;
System.out.println(p.getId());
System.out.println(p.getName());
System.out.println(p.getAge());
}
System.out.println(ois.read());
Object ob2 = ois.readObject();
if (ob2!= null){
Person p= (Person)ob2;
System.out.println(p.getId());
System.out.println(p.getName());
System.out.println(p.getAge());
}
System.out.println(ois.read());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
ois.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class Person implements Serializable {
private static final long serialVersionUID = 2243668234110136779L;
int age;
Person(int age) {
this.age = age;
}
}
public class Test {
public static void main(String[] args) throws Exception {
Person[] persons = new Person[3];
persons[0] = new Person(1);
persons[1] = new Person(5);
persons[2] = new Person(20);
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("D:\\test"));
oos.writeInt(persons.length);
for (int i = 0; i < persons.length; i++) {
oos.writeObject(persons[i]);
}
oos.close();
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("D:\\test"));
int num = ois.readInt();
persons = new Person[num];
for (int i = 0; i < num; i++) {
persons[i] = (Person)ois.readObject();
}
ois.close();
for (int i = 0; i < persons.length; i++) {
System.out.println(persons[i].age);
}
}
}
package com.donghe.package1;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
public class ObjectIntputStreamDemo {
public static void main(String[] args){
ObjectInputStream ois =null;
try {
FileInputStream fileStream =new FileInputStream("e:\\person.tmp");
ois = new ObjectInputStream(fileStream);
while (true) {
Object ob = ois.readObject();
if(ob!=null){
Person p= (Person)ob;
System.out.println(p.getId());
System.out.println(p.getName());
System.out.println(p.getAge());
}
}
} catch(EOFException e){
System.out.println("类对象已完全读入");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
ois.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
能输出N个类对象的属性
public static Person readPerson(ObjectInputStream ois){
Object obj = ois.readObject();
return (Person)obj
}