新学习内容
该流做的是对象持久化处理
java.io.Serializable
空接口,向jvm声明,实现了这个接口的对象即可被存储到文件中
transient
(译:暂时)
声明不存储到文件中的属性
ObjectInputStream和ObjectOutputStream
对象输入输出流
建立雇员对象:
代码语言:javascript复制package cn.hxh.io.other;
public class Employee implements java.io.Serializable {
private transient String name;
private double salary;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public Employee(String name, double salary) {
super();
this.name = name;
this.salary = salary;
}
public Employee() {
super();
}
}
进行读取写入完整代码
代码语言:javascript复制package cn.hxh.io.other;
import java.io.*;
import java.util.Arrays;
public class ObjectDemo01 {
public static void main(String[] args) throws IOException, ClassNotFoundException {
write("D:/aa/aa.txt");
read("D:/aa/aa.txt");
}
public static void read(String destPath) throws IOException, ClassNotFoundException {
File dest = new File(destPath);
ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(dest)));
Object obj = ois.readObject();
Employee emp = null;
if (obj instanceof Employee) emp = (Employee) obj;
System.out.println(emp.getName());
System.out.println(emp.getSalary());
System.out.println(emp.getClass());
obj = ois.readObject();
int[] i = null;
if (obj instanceof int[]) i = (int[]) obj;
System.out.println(Arrays.toString(i));
ois.close();
}
public static void write(String destPath) throws IOException {
Employee emp = new Employee("aaa", 10000);
File dest = new File(destPath);
ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(dest)));
oos.writeObject(emp);
int[] i = {1, 2, 3, 4, 5};
oos.writeObject(i);
oos.flush();
oos.close();
}
}