一、对象流是什么?
用于存储和读取基本数据类型数据或对象的处理流。
它的强大之处就是可以把Java中的对象写入到数据源中,也能把对象从数据源中还原回来。
二、代码实例
1.学生类代码
代码如下(示例):
ipackage jiruan.Jiruan322.Lianxi;
import java.io.Serializable;
public class Student implements Serializable {
private String name;
private String age;
private String sex;
public Student() {
}
public Student(String name, String age, String sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
/**
* 获取
* @return name
*/
public String getName() {
return name;
}
/**
* 设置
* @param name
*/
public void setName(String name) {
this.name = name;
}
/**
* 获取
* @return age
*/
public String getAge() {
return age;
}
/**
* 设置
* @param age
*/
public void setAge(String age) {
this.age = age;
}
/**
* 获取
* @return sex
*/
public String getSex() {
return sex;
}
/**
* 设置
* @param sex
*/
public void setSex(String sex) {
this.sex = sex;
}
public String toString() {
return "Student{name = " + name + ", age = " + age + ", sex = " + sex + "}";
}
}
2.测试类代码:
package jiruan.Jiruan322.Lianxi;
import javax.tools.FileObject;
import java.io.*;
import java.util.Scanner;
public class Test {
public static void main(String[] args) throws IOException, ClassNotFoundException {
File f=new File("D:\\1234.txt");
FileOutputStream fos=new FileOutputStream(f);
ObjectOutputStream oos=new ObjectOutputStream(fos);
FileInputStream fis=new FileInputStream(f);
ObjectInputStream ois=new ObjectInputStream(fis);
Scanner input=new Scanner(System.in);
System.out.println("请输入");
String str=input.next();
while (!str.equals("exit")){
String[] str1=str.split("#");
oos.writeObject(new Student(str1[0],str1[1],str1[2]));
str=input.next();
}
try{
Object object=ois.readObject();
while (object!=null){
System.out.println((Student)object);
object=ois.readObject();
}
}catch (Exception e){
System.out.println("dd");
}
ois.close();
oos.close();
}
}