作业:
创建多个对象并将其写入至文件1,然后利用字节流的方式复制文件1活动文件2,再读取文件2中的对象,判断其使用字节流复制后是否对象是否可以正确读取
import java.io.*;
public class Test {
public static void main(String[] args) throws IOException, ClassNotFoundException {
//输出对象
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("d:\\object.txt"));
int i=1;
while (i<99) {
oos.writeObject(new Stu("name"+i,i));
i++;
}
oos.close();
//复制文件
FileInputStream file = new FileInputStream("d:\\object.txt");
FileOutputStream file1 = new FileOutputStream("d:\\object_copy.txt");
byte[] b = new byte[1024];
int len = 0;
while ((len=file.read(b)) != -1) {
file1.write(b,0,len);
}
file.close();
file1.close();
//输入对象
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("d:\\object_copy.txt"));
Stu s = (Stu) ois.readObject();
System.out.println(s.name+" "+s.age);
ois.close();
}
}
//输出对象的类必须实现Serializable接口
class Stu implements Serializable {
String name;
int age;
public Stu(String name,int age) {
this.name = name;
this.age = age;
}
}
结论:
可以正确获取对象!