java对象序列化 传输 保存

package com;

import java.io.Serializable;

public class Teacher implements Serializable
{
private static final long serialVersionUID = -8732868773377627151L;
private String name;
private Student student;
public String getName()
{
   return name;
}
public void setName(String name)
{
   this.name = name;
}
public Student getStudent()
{
   return student;
}
public void setStudent(Student student)
{
   this.student = student;
}
public String toString()
{
   return "Teacher [name=" + name + ", student=" + student + "]";
}

}

package com;

import java.io.Serializable;

public class Student implements Serializable
{
private static final long serialVersionUID = 7194554035111554277L;
private String name;
private Teacher teacher;
public String getName()
{
   return name;
}
public void setName(String name)
{
   this.name = name;
}
public Teacher getTeacher()
{
   return teacher;
}

public void setTeacher(Teacher teacher)
{
   this.teacher = teacher;
}

public String toString()
{
   return "Student [name=" + name + ", teacher=" + teacher + "]";
}

}

package com;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class Obj2File
{
public static void main(String[] args) throws FileNotFoundException, IOException
{
   Teacher teacher = new Teacher();
   teacher.setName("Tony");
  
   Student student = new Student();
   student.setName("Danny");
   student.setTeacher(teacher);
   teacher.setStudent(student);
  
   System.out.println("将Teacher对象写入到文件中...");
   ByteArrayOutputStream oas = new ByteArrayOutputStream();
   ObjectOutputStream oos = new ObjectOutputStream(oas);
   //将Teacher对象压入oas
   oos.writeObject(teacher);
   StringBuffer sb = new StringBuffer();
   byte bytes[] = oas.toByteArray();
   //将oas输出
   for(int i=0;i<bytes.length;i++){
    System.out.print(bytes[i]+" ");
    sb.append(bytes[i]);
   }
   System.out.println("\n"+sb.toString());
   oos.close();
   oas.close();
  
   System.out.println("将Teacher对象写入到文件C:\\Teacher.tmp中...");
   ObjectOutputStream oos2 = new ObjectOutputStream(
     new FileOutputStream("C:/Teacher.tmp"));
   oos2.writeObject(teacher);
   oos2.close();
   System.out.println("完成!");
}

}

package com;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;

public class File2Obj
{
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException
{
   ObjectInputStream ois = new ObjectInputStream(new FileInputStream("C:/Teacher.tmp"));
   Teacher teacher = (Teacher) ois.readObject();
   System.out.println(teacher.getStudent().getTeacher().getName());
   ois.close();
}
}

你可能感兴趣的:(java,C++,c,C#)