Java 对象流详解
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class Work2 implements Serializable {
private static final long serialVersionUID = 1L;
String name;
int age;
public Work2(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String toString() {
return "Work2 [name=" + name + ", age=" + age + "]";
}
}
class Ois{
public static void main(String[] args) {
try(
FileInputStream fis = new FileInputStream("文件名或文件");
ObjectInputStream ois = new ObjectInputStream(fis)
) {
//Object ob = ois.readObject();
Work2 work = (Work2)ois.readObject();
System.out.println(work);
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Oos{
public static void main(String[] args) {
Work2 work = new Work2("小明", 12);
try(
FileOutputStream fos = new FileOutputStream("文件名或文件");
ObjectOutputStream oos = new ObjectOutputStream(fos);
) {
oos.writeObject(work);
} catch (Exception e) {
e.printStackTrace();
}
}
}
对象流重点:
需要存储的对象必须实现可序列化接口Serializable,否则会抛出异常NotSerializabileException;
需要加版本号:private static final long serialVersionUID = 1L;
对象输出流经过oos.writeObject(),首先将对象按照其结构转换为一组字节,这个过程为对象序列化;
对象输入流ois.readObject(),和上面是反过来的,把字节转换为对象。
对象输入流和输出流,其实所有的对象默认都是超类Object,然后可以强制转换为所需要的对象;