代码如下,先是Students类:
package TestDemo;
import java.io.Serializable;
import java.util.ArrayList;
public class Students implements java.io.Serializable {
private String number;
private String name;
//自定义序列化,用于可以不传递不需要的对象或者对代码进行性能的优化
private transient int age;
public Students(){
}
public Students(String number, String name, int age) {
super();
this.number = number;
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "学号"+this.getNumber()+this.getName()+this.getAge();
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
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;
}
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException{
s.defaultWriteObject();//将java虚拟机默认序列化的元素进行序列化
s.writeInt(age);//自己完成age的序列化
}
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
s.defaultReadObject();
this.age=s.readInt();
}
}
将文件中保存的对象进行输出:
<pre name="code" class="java">package TestDemo;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.lang.reflect.Array;
import java.util.ArrayList;
//自定义序列化
public class Define {
//用总计的方法进行序列化
public static void d1() throws Exception{
File file1= new File("t3.dat");
if(!file1.exists()){
file1.createNewFile();
}
ObjectOutputStream oos= new ObjectOutputStream(
new FileOutputStream(file1));
Students stu= new Students("2018","tom",90);
oos.writeObject(stu);//添加文件进对象
oos.flush();
oos.close();
System.out.println("添加成功");
//反序列化,将文件中的对象读写出来
ObjectInputStream ois= new ObjectInputStream(
new FileInputStream(file1));
Students s1=(Students)ois.readObject();
System.out.println(s1);
ois.close();
}
public static void main(String[] args) {
try {
d1();
} catch (Exception e) {
e.printStackTrace();
}
}
}