Java-使用序列化保存对象数据到文件学习总结

1.序列化

1.1 什么是序列化

  • Java当中提供了一种序列化操作的方式,用一个字节序列来表示一个对象,该字节序列中保存了对象的属性、对象的数据、对象的类型。把字节序列化保存到文件中,就可以做到持久化保存数据内容。

1.2 如何将对象数据序列化保存到文件

使用ObjectOutputStream完成序列化操作:

Constructor:
  ObjectOutputStream(OutputStream out)
Method:
  void writeObject(Object obj)

/**
	 * 使用序列化实现数据的保存
	 * 
	 * @param sm StudentManager类对象
	 */
	public static void saveDataUseSeri(StudentManager sm) {
		ObjectOutputStream os = null;
		
		try {
			os = new ObjectOutputStream(new FileOutputStream(
					new File("E:/aaa/data.txt")));
			
			/*
			 * 将count的值包装成一个Student类对象,赋值给id值,添加到
			 * StudentManager对象当中,因为是尾插法添加所以在最后一个位置上
			 */
			sm.add(new Student(Student.getCount()));
			
			/*
			 * 将Studentmanager类对象序列化保存到文件中
			 */
			os.writeObject(sm);
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if(os != null) {
				try {
					os.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

1.3 如何将文件中的对象数据反序列化

使用ObjectOutputStream完成序列化操作:

Constructor:
  ObjectInputStream(InputStream in)
Method:
  Object readObject( )

/**
	 * 使用反序列化读取数据
	 * 
	 * @param sm StudentManager类对象
	 */
	public static void readDataSeri(StudentManager sm) {
		ObjectInputStream is = null;
		
		try {
			is = new ObjectInputStream(new FileInputStream(
				new File("E:/aaa/data.txt")));
			
			/*
			 * 反序列化得到一个StudentManager类对象
			 */
			StudentManager studentManager = (StudentManager)is.readObject();
			
			/*
			 * 由StudentManager类对象调用getAllStudent()
			 * 得到该对象中的所有学生数据,为一个Student数组stu
			 */
			Student[] stu = studentManager.getAllStudent();
			
			/*
			 * 遍历stu数组,将从 0 - 倒数第二个元素添加到StudentManager对象sm中
			 */
			for(int i = 0; i < stu.length - 1; i++) {
				sm.add(stu[i]);
			}
			
			/*
			 * 因为数组中的最后一个元素,一个只有id号的Student类对象
			 * 而且这个id号是count值,所以由getId()方法取得这个id
			 * 赋值给Student中的count,从而达到目的
			 */
			Student.setCount(stu[stu.length - 1].getId());
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if(is != null) {
				try {
					is.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

1.4 序列化的注意事项

  1. 如果一个类要进行序列化操作,那么必须遵从java.io.Serializable接口,不然无法进行序列化操作,该接口是一个标识接口。
  2. 序列化之后的每一个类都会有一个serialVersionUID,该编号在使用过程中,序列化与反序列化必须一致。
  3. transient关键字,瞬态 , 使用该关键字的修饰的成员变量不会被序列化。
发布了14 篇原创文章 · 获赞 16 · 访问量 5477

猜你喜欢

转载自blog.csdn.net/cccccv_/article/details/104700956