输出流
package com.test.file;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class TestObjectOutputStream {
public static void main(String[] args) {
File file=new File("/Users/yangjunbo/kaifa/Test/person.data");
FileOutputStream fileOutputStream;
try {
fileOutputStream = new FileOutputStream(file);
ObjectOutputStream objectOutputStream=new ObjectOutputStream(fileOutputStream);
Person person=new Person("yaoming",36);
objectOutputStream.writeObject(person);
objectOutputStream.close();
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
输入流
package com.test.file;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
public class TestObjectInputStream {
public static void main(String[] args) {
File file=new File("/Users/yangjunbo/kaifa/Test/person.data");
FileInputStream fileInputStream;
try {
fileInputStream = new FileInputStream(file);
ObjectInputStream objectInputStream=new ObjectInputStream(fileInputStream);
Person person=(Person)(objectInputStream.readObject());
System.out.println(person);
objectInputStream.close();
fileInputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Person类
package com.test.file;
import java.io.Serializable;
public class Person implements Serializable {
public static final long serialVersionUID=342343423l;
private static String name;
public transient int age;
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;
}
public Person()
{}
public Person(String name,int age)
{
this.name=name;
this.age=age;
}
public String toString()
{
return "Person[name="+this.name+",age="+this.age+"]";
}
}