将java对象写入文件,或从文件读取转为java对象
ObjectInputStream、ObjectOutputStream
1.编写JavaBean
package test.others;
import java.io.Serializable;
public class Employee implements Serializable{
private static final long serialVersionUID = -8097676852956481296L;
// 使用transient标明该字段不需要写入文件
private transient String name;
private double salary;
public Employee() {
}
public Employee(String name, double salary) {
super();
this.name = name;
this.salary = 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;
}
}
2.测试对象流操作
package test.others;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Arrays;
public class ObjectDemo01 {
public static void main(String[] args) throws IOException, ClassNotFoundException {
seri("E:/test/seri.txt");
read("E:/test/seri.txt");
}
public static void read(String destPath) throws ClassNotFoundException, IOException {
File file = new File(destPath);
ObjectInputStream is = new ObjectInputStream(new BufferedInputStream(new FileInputStream(file)));
Object obj = is.readObject();
if (obj instanceof Employee) {
Employee emp=(Employee)obj;
System.out.println(emp.getName());
System.out.println(emp.getSalary());
}
obj =is.readObject();
int[] arr=(int[])obj;
System.out.println(Arrays.toString(arr));
is.close();
}
public static void seri(String desPath) throws IOException {
Employee emp = new Employee("bjxst", 10000);
int[] arr = {1,2,3,4};
File dest = new File(desPath);
ObjectOutputStream dos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(dest)));
dos.writeObject(emp);
dos.writeObject(arr);
dos.close();
}
}