对象流
public class ObjectInputOutputStreamTest {
@Test
public void testObjectOutputStream(){
ObjectOutputStream oos
= null
;
try {
oos
= new ObjectOutputStream(new FileOutputStream("object.dat"));
oos
.writeObject(new String("我爱敲代码"));
oos
.flush();
oos
.writeObject(new Person("阿昌",21));
oos
.flush();
} catch (IOException e
) {
e
.printStackTrace();
} finally {
if (oos
!= null
){
try {
oos
.close();
} catch (IOException e
) {
e
.printStackTrace();
}
}
}
}
@Test
public void testObjectInputStream(){
ObjectInputStream ois
= null
;
try {
ois
= new ObjectInputStream(new FileInputStream("object.dat"));
Object obj
= ois
.readObject();
String str
= (String
)obj
;
Person p
=(Person
)ois
.readObject() ;
System
.out
.println(str
);
System
.out
.println(p
);
} catch (IOException e
) {
e
.printStackTrace();
} catch (ClassNotFoundException e
) {
e
.printStackTrace();
} finally {
if (ois
!= null
){
try {
ois
.close();
} catch (IOException e
) {
e
.printStackTrace();
}
}
}
}
}
Person类
public class Person implements Serializable {
public static final long serialVersionUID
= 454613272L
;
private String name
;
private Integer age
;
public Person() {
}
public Person(String name
, Integer age
) {
this.name
= name
;
this.age
= age
;
}
public String
getName() {
return name
;
}
public void setName(String name
) {
this.name
= name
;
}
public Integer
getAge() {
return age
;
}
public void setAge(Integer age
) {
this.age
= age
;
}
@Override
public String
toString() {
return "Person{" +
"name='" + name
+ '\'' +
", age=" + age
+
'}';
}
}
转载请注明原文地址:https://blackberry.8miu.com/read-3944.html