• 对象序列化(serializable)

序列化读:ObjectInputStream  ois=new ObjectInputStream(new FileInputStream("./ggg.txt"));

序列化写: ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("./ggg.txt"));

序列化对象参数为I/O字节流读写对象。

1.将对象序列化写到本地

新建学生类实现序列化接口,当对象中某一个属性或方法不需要序列化时,在属性或方法前加:transient.

import java.io.Serializable;
public class Student implements Serializable {
private String name;
transient private int age; //某一个属性不需要序列化时加:transient
private String id;
public void eat(){
System.out.println("吃吃");
}
//这里需要添加set和get方法

}

创建对象,实现对象序列化写到本地文件ggg.txt

@Test
public void test12(){
Student stu = new Student();
stu.setName("序列化测试");
stu.setAge(20);
stu.setId("21432423");
ObjectOutputStream oos=null;
try {
oos=new ObjectOutputStream(new FileOutputStream("./ggg.txt"));
oos.writeObject(stu); //将一个对象写入到本地 } catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (oos != null) {
oos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
测试结果:�� sr com.lanou.Studenta��N0�� L idt Ljava/lang/String;L nameq ~ xpt 21432423t 序列化测试 2.反序列化读,将本地文件ggg.txt文件反序列化读回计算机
@Test
public void test13(){ //将序列化好的对象,读回计算机
//反序列化 ObjectInputStream ois=null;
try {
ois=new ObjectInputStream(new FileInputStream("./ggg.txt"));
Object o=ois.readObject();
System.out.println(o); } catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}finally {
try {
if (ois != null) {
ois.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
测试结果:
Student{name='序列化测试', age=0, id='21432423'}

Process finished with exit code 0
 

最新文章

  1. Angular2学习之开发环境构建
  2. Tiled Map地图编辑器键盘快捷键
  3. fork
  4. AppStore提审攻略
  5. svn merge部分的详细说明
  6. 说一说window.parent
  7. reactjs 入门
  8. github的简单使用
  9. LVDS、CVBS
  10. Linux(2)---记录一次线上服务 CPU 100%的排查过程
  11. 初识css预处理器:Sass、LESS
  12. 最简单的操作 jetty IDEA 【debug】热加载
  13. 函数内联 inline,__inline,__forceinline
  14. Spring Boot -05- 多模块结构项目构建与测试(详细图文教程)IDEA 版
  15. Spring Boot 验证表单
  16. [转帖]Git数据存储的原理浅析
  17. 喵哈哈村的魔法考试 Round #4 (Div.2) 题解
  18. Python 自定义异常处理Error函数
  19. tcp 大文件上传 ,切换目录 及登陆文件加盐处理
  20. col标签的相关实验

热门文章

  1. 31. Next Permutation (Array; Math)
  2. python全栈考试
  3. Illegal mix of collations for operation 'like' while searching with Ignited-Datatables
  4. Centos 7 安装和配置Redis
  5. scrollView不能进行滚动
  6. 打开Android Studio时报Unable to access Android SDK add-on list
  7. Kubernetes基本原理与示例
  8. Object 和 JSON 区别联系
  9. [转]解决Mysql InnoDB: Failing assertion: ret || !assert_on_error问题
  10. Postgresql 日志审计