java_对象序列化
2024-08-23 03:41:45
- 对象序列化(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
最新文章
- Angular2学习之开发环境构建
- Tiled Map地图编辑器键盘快捷键
- fork
- AppStore提审攻略
- svn merge部分的详细说明
- 说一说window.parent
- reactjs 入门
- github的简单使用
- LVDS、CVBS
- Linux(2)---记录一次线上服务 CPU 100%的排查过程
- 初识css预处理器:Sass、LESS
- 最简单的操作 jetty IDEA 【debug】热加载
- 函数内联 inline,__inline,__forceinline
- Spring Boot -05- 多模块结构项目构建与测试(详细图文教程)IDEA 版
- Spring Boot 验证表单
- [转帖]Git数据存储的原理浅析
- 喵哈哈村的魔法考试 Round #4 (Div.2) 题解
- Python 自定义异常处理Error函数
- tcp 大文件上传 ,切换目录 及登陆文件加盐处理
- col标签的相关实验
热门文章
- 31. Next Permutation (Array; Math)
- python全栈考试
- Illegal mix of collations for operation 'like' while searching with Ignited-Datatables
- Centos 7 安装和配置Redis
- scrollView不能进行滚动
- 打开Android Studio时报Unable to access Android SDK add-on list
- Kubernetes基本原理与示例
- Object 和 JSON 区别联系
- [转]解决Mysql InnoDB: Failing assertion: ret || !assert_on_error问题
- Postgresql 日志审计