| 序列化:一个对象可以被表示为一个字节序列,该字节序列包括该对象的数据、有关对象的类型的信息和存储在对象中数据的类型 |
| 反序列化:将序列化对象写入文件之后,可以从文件中读取出来,并且对它进行反序列化 |
| 一个类的对象要想序列化成功,必须满足两个条件: |
| 该类必须实现 java.io.Serializable 接口。 |
| 该类的所有属性必须是可序列化的。如果有一个属性不是可序列化的,则该属性必须注明是短暂的 |
| |
| public class Employee implements java.io.Serializable |
| { |
| public String name; |
| public String address; |
| public transient int SSN; |
| public int number; |
| public void mailCheck() |
| { |
| System.out.println("Mailing a check to " + name |
| + " " + address); |
| } |
| } |
- 实例化了一个 Employee 对象,并将该对象序列化到一个文件中
| public class SerializeDemo |
| { |
| public static void main(String [] args) |
| { |
| Employee e = new Employee(); |
| e.name = "Reyan Ali"; |
| e.address = "Phokka Kuan, Ambehta Peer"; |
| e.SSN = 11122333; |
| e.number = 101; |
| try |
| { |
| FileOutputStream fileOut = |
| new FileOutputStream("/tmp/employee.ser"); |
| ObjectOutputStream out = new ObjectOutputStream(fileOut); |
| out.writeObject(e); |
| out.close(); |
| fileOut.close(); |
| System.out.printf("Serialized data is saved in /tmp/employee.ser"); |
| }catch(IOException i) |
| { |
| i.printStackTrace(); |
| } |
| } |
| } |
| public class DeserializeDemo |
| { |
| public static void main(String [] args) |
| { |
| Employee e = null; |
| try |
| { |
| FileInputStream fileIn = new FileInputStream("/tmp/employee.ser"); |
| ObjectInputStream in = new ObjectInputStream(fileIn); |
| e = (Employee) in.readObject(); |
| in.close(); |
| fileIn.close(); |
| }catch(IOException i) |
| { |
| i.printStackTrace(); |
| return; |
| }catch(ClassNotFoundException c) |
| { |
| System.out.println("Employee class not found"); |
| c.printStackTrace(); |
| return; |
| } |
| System.out.println("Deserialized Employee..."); |
| System.out.println("Name: " + e.name); |
| System.out.println("Address: " + e.address); |
| System.out.println("SSN: " + e.SSN); |
| System.out.println("Number: " + e.number); |
| } |
| } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术
2021-05-07 vue2.0入门