import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
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;
import java.util.Arrays;
/*
* 对象流 : 数据+类型
* 序列化: 就把对象的状态转为可存储或者可传输的状态的过程
* 序列化输出流 ObjectOutputStream()
* 反序列化输入流 ObjectInputStream()
* 新增方法--> readObject() writeObject() 不能多态使用
*
* 先序列化->后反序列化
*
* 不是所有的类都能够序列化 实现java.io.Serializable接口
* 读写的顺序要保持一致
* 不是所有的属性都需要序列化 transient关键字修饰
* 静态的内容不能序列化
* 如果父类有实现了Serializable,子类可以所有成员进行序列化
* 如果子类实现了父类没有实现,子类只能序列化自己独有的内容
*/
public class ObjectDemo01 {
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
out("D:/bighammer.txt");
in("D:/bighammer.txt");
}
//反序列化输入流
public static void in(String path) throws FileNotFoundException, IOException, ClassNotFoundException{
//选择流
ObjectInputStream is=new ObjectInputStream(new BufferedInputStream(new FileInputStream(path)));
//读取
Object obj=is.readObject();
int[] arr=(int[]) is.readObject();
System.out.println(obj);
System.out.println(Arrays.toString(arr));
//关闭
is.close();
}
//序列化输出流
public static void out(String path) throws FileNotFoundException, IOException{
//选择流
ObjectOutputStream os=new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(path)));
//写出
Person p=new Person(01,"赵六",18);
os.writeObject(p);
os.writeObject(new int[]{1,2,3,4});
//刷出
os.flush();
//关闭
os.close();
//p.setId(10000);
}
}
class Person implements Serializable{
private /*static*/ int id;
private transient String name;
private int age;
public Person() {
// TODO Auto-generated constructor stub
}
public Person(int id, String name, int age) {
super();
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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;
}
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}
java的对象流
最新推荐文章于 2021-08-31 17:09:01 发布