200字范文,内容丰富有趣,生活中的好帮手!
200字范文 > java 序列化对象 serializable 读写数据的实例

java 序列化对象 serializable 读写数据的实例

时间:2020-03-03 15:06:54

相关推荐

java 序列化对象 serializable 读写数据的实例

下面,小编带您去了解一下java 序列化对象 serializable 读写数据的实例,生活就是不断的发现新事物,get新技能~

序列化对象:

代码如下:

package ;

import ;

import ;

@SuppressWarnings("serial")

public class Student implements Serializable

{

private String name;

private String id;

private int age;

private ListStudent students;

public String getName()

{

return name;

}

public void setName(String name)

{

= name;

}

public String getId()

{

return id;

}

public void setId(String id)

{

this.id = id;

}

public int getAge()

{

return age;

}

public void setAge(int age)

{

this.age = age;

}

public ListStudent getStudents()

{

return students;

}

public void setStudents(ListStudent students)

{

= students;

}

@Override

public String toString()

{

StringBuffer stringBuffer = new StringBuffer();

("id:" + this.id).append("n");

("name:" + ).append("n");

("age:" + this.age).append("n");

return ();

}

}

代码如下:

package ;

import ;

import ;

import ;

import ;

import ;

import ;

import ;

public class SaveStudent

{

private Student student;

// 序列化文件保存位置

private String path = "C:/";

public void writeStudent()

{

ListStudent students = new ArrayListStudent();

student = new Student();

Student student1 = new Student();

();

("");

("张");

();

Student student2 = new Student();

();

("");

("张");

();

Student student3 = new Student();

();

("");

("张");

();

Student student4 = new Student();

();

("");

("张");

Student student41 = new Student();

();

("");

("张");

ListStudent students4 = new ArrayListStudent();

();

();

();

();

("");

("张");

();

try

{

ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(path));

();

();

}

catch (IOException e)

{

// TODO Auto-generated catch block

();

}

("写完");

}

public void readStudent()

{

try

{

ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(path));

student = (Student) ();

(());

();

}

catch (Exception e)

{

();

}

("读完");

}

@Override

public String toString()

{

readStudent();

StringBuffer stringBuffer = new StringBuffer(100);

studentToString(stringBuffer, student);

return ();

}

public void studentToString(StringBuffer stringBuffer, Student studentObj)

{

if (student != null)

{

("id:" + ()).append("n");

if (() != null)

{

("n[n");

for (Student bean : ())

{

studentToString(stringBuffer, bean);

}

("n]n");

}

}

}

}

测试类:

代码如下:

package ;

public class Test

{

/**

* @param args

*/

public static void main(String[] args)

{

SaveStudent saveStudent = new SaveStudent();

// 1 先执行写入文件

// ();

// 2 再读取

(saveStudent);

("读完");

}

}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。