对对象包装类ObjectInputStream/ObjectOutputStream的应用
2016-04-03 00:13
477 查看
实现代码如下:
Student.java文件的代码:
import java.io.*; public class Student implements Serializable { int id; String name; int age; String department; public Student(int id,String name,int age,String department) { this.id = id; this.name = name; this.age = age; this.department = department; } }
Serialization.java文件的代码:
import java.io.*; public class Serialization { public static void main(String[] args) throws Exception { Student stu1 = new Student(19,"zhangsan",25,"huaxue"); Student stu2 = new Student(20,"lisi",23,"wuli"); FileOutputStream fos = new FileOutputStream("Student.txt"); ObjectOutputStream os = new ObjectOutputStream(fos); os.writeObject(stu1); os.writeObject(stu2); os.close(); FileInputStream fis = new FileInputStream("Student.txt"); ObjectInputStream is = new ObjectInputStream(fis); Student stu3 = (Student)is.readObject(); Student stu4 = (Student)is.readObject(); is.close(); System.out.println("id:"+stu3.id); System.out.println("name:"+stu3.name); System.out.println("age:"+stu3.age); System.out.println("department:"+stu3.department); System.out.println("id:"+stu4.id); System.out.println("name:"+stu4.name); System.out.println("age:"+stu4.age); System.out.println("department:"+stu4.department); } }
运行结果:
Student.txt文件里面是乱码,因为使用对象包装类写入的内容只有此对象包装类才才能对写出正确的内容。使用对象包装类的好处就是可以直接实现对对象的读写,减少了很多操作。
相关文章推荐
- 数组与Object的关系及其反射类型
- NSObject
- 深入理解Objective-C:Category(下)
- 深入理解Objective-C:Category(上)
- Object wait T ms to run again
- Object wait and notify
- Objective-c 对象与类 继承
- Objective-c 对象与类 封装
- 一张图看懂Function和Object的关系及简述instanceof运算符
- Qt 向word中插入文字(使用QAxWidget和QAxObject)
- SPRING IN ACTION 第4版笔记-第十一章Persisting data with object-relational mapping-006Spring-Data的运行规则(@EnableJpaRepositories、<jpa:repositories>)
- 解决循环操作ObjectInputStream的readObject()方法的EOF异常
- 执行命令行并等待完成(使用WaitForSingleObject达到目的)
- JSONObject转换JSON--将Date转换为指定格式
- SPRING IN ACTION 第4版笔记-第十一章Persisting data with object-relational mapping-005Spring-Data-JPA例子的代码
- SPRING IN ACTION 第4版笔记-第十一章Persisting data with object-relational mapping-004JPA例子的代码
- 使用 jackson ObjectMapper将java对象转换为json对象
- QT中的QMetaObject
- 设备模型之kobject,kset及其关系
- SPRING IN ACTION 第4版笔记-第十一章Persisting data with object-relational mapping-003编写JPA-based repository( @PersistenceUnit、 @PersistenceContext、PersistenceAnnotationBeanPostProcessor)