Java 对象流和序列化
对象流有两个类:
(1)ObjectOutputStream:将对象的基本数据类型和图形进行序列化
(2)ObectInputStream:对已保存的序列化文件进行反序列化
序列化一组对象可使用对象数组的方式。
transient关键字:
若某个成员变量被transient修饰,那么当对象被序列化的时候,该变量不会被保存。
代码示例:
package com.seven.javaSE; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.Serializable; public class ObejctSerializable { public static void main(String[] args) { saveObejct(); readObject(); } //将对象序列化,保存在本地 public static void saveObejct() { Animal cat = new Animal(1,"中国",2); try { OutputStream out = new FileOutputStream("c:/TestFile/cat.obj"); ObjectOutputStream oos = new ObjectOutputStream(out); oos.writeObject(cat); oos.close(); System.out.println("对象序列化完成"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } //将对象反序列化,读取被保存的对象 public static void readObject() { try { InputStream in = new FileInputStream("C:/TestFile/cat.obj"); ObjectInputStream ois = new ObjectInputStream(in); Animal cat = (Animal)ois.readObject(); System.out.println(cat); System.out.println("对象反序列化成功"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } } /* * 一个类对象要想要保存在物理介质或在网络上传输,必须要实现Serializable接口 * 此接口是一个标记接口,里面没有任何内容 */ class Animal implements Serializable{ // private static final long serialVersionUID = 1L; private int id; private String address; private int age; public Animal(int id, String address, int age) { super(); this.id = id; this.address = address; this.age = age; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Animal [id=" + id + ", address=" + address + ", age=" + age + "]"; } }
本文来自博客园,作者:藤原豆腐渣渣,转载请注明原文链接:https://www.cnblogs.com/javafufeng/p/16387007.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现