刚好接触到要用的思路,扩充下
1 对象序列化
1.1 对象要序列化要实现Serializable接口
1.2 然后通过ObjectInputStream 对象读入流来读入一个对象
| new ObjectOutputStream(new xxOutputStream("")) |
| new的时候传入一个读入流 |
1.3 需要申明一个序列化版本号
| private static final long serialVersionUID = ; |
| |
| |
| ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("")); |
| |
| oos.writeObject(); |
| |
| |
| ObjectInputStream ois = new ObjectInputStream(new FileInputStream("")); |
| |
| Object o = ois.readObject(); |
1.4 序列化对象——文件
| public class Main { |
| public static void main(String[] args) throws ClassNotFoundException { |
| Vector<Integer> list1 = new Vector<>(); |
| |
| list1.add(2); |
| |
| |
| try { |
| FileOutputStream fileOutputStream = new FileOutputStream("data.txt"); |
| |
| ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream); |
| objectOutputStream.writeObject(list1); |
| |
| objectOutputStream.flush(); |
| |
| FileInputStream fileInputStream = new FileInputStream("data.txt"); |
| ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream); |
| Object o = objectInputStream.readObject(); |
| List<Integer> list2 = (List<Integer>) o; |
| |
| System.out.println(list2.get(0)); |
| } catch (IOException e) { |
| e.printStackTrace(); |
| } |
| |
| } |
| |
| } |
1.5序列化对象——字节
| public class Main { |
| public static void main(String[] args) throws ClassNotFoundException { |
| Vector<Integer> list1 = new Vector<>(); |
| |
| list1.add(2); |
| |
| try { |
| |
| ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); |
| |
| ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); |
| objectOutputStream.writeObject(list1); |
| |
| objectOutputStream.flush(); |
| |
| |
| |
| byte[] bytes = byteArrayOutputStream.toByteArray(); |
| |
| ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); |
| ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); |
| Object o = objectInputStream.readObject(); |
| List<Integer> list2 = (List<Integer>) o; |
| |
| System.out.println(list2.get(0)); |
| } catch (IOException e) { |
| e.printStackTrace(); |
| } |
| |
| } |
| } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)