ObjectInputStream和ObjectOutputStream
来源:互联网 发布:java包装1年项目经验 编辑:程序博客网 时间:2024/05/20 23:07
1.
ObjectInputStream与ObjectOutputStream类所读写的对象必须实现Serializable接口,ObjectOutputStream是把对象堆中的数据存写到文件中,所以对象中的transient和static类型成员变量不会被读取和写入;
注意:如果没有实现Serializable接口,则出错。这是为了保证能把对象写入到文件,并能再把对象读回到程序中的缘故。
对数据其中转作用的是文件,ObjectOutputStream把对象存入文件, ObjectInputStream从文件中读取数据
2.import java.io.*;
public class serializtion {
public static void main(String[] args)throws IOException{
Student s1=new Student("wangwu", 1, 18, "数学"); //要被存储的对象
Student s2=new Student("lisi", 2, 19, "物理");
//把对象存入文件中
FileOutputStream fout=new FileOutputStream("student.txt");
ObjectOutputStream out=new ObjectOutputStream(fout);out.writeObject(s1);
out.writeObject(s2);
out.close();
//从文件中读取对象
FileInputStream fin=new FileInputStream("student.txt");ObjectInputStream in=new ObjectInputStream(fin);
try {
s1=(Student) in.readObject();
s2=(Student) in.readObject();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
in.close();
System.out.print("name:"+s1.name);
System.out.print(" id:"+s1.id);
System.out.print(" age:"+s1.age);
System.out.println(" department:"+s1.department);
System.out.print("name:"+s2.name);
System.out.print(" id:"+s2.id);
System.out.print(" age:"+s2.age);
System.out.println(" department:"+s2.department);
}
}
3.import java.io.*;
//要存入的对象所属的类
public class Student implements Serializable {String name;
int id ;
int age;
String department;
public Student(String name, int id, int age, String department) {
this.age = age;
this.department = department;
this.id = id;
this.name = name;
}
}
0 0
- ObjectInputStream和ObjectOutputStream
- ObjectInputStream和ObjectOutputStream
- ObjectOutputStream和ObjectInputStream
- ObjectInputStream和ObjectOutputStream
- ObjectOutputStream和ObjectInputStream
- Java ObjectInputStream 和 ObjectOutputStream
- ObjectOutputStream和ObjectInputStream
- ObjectInputStream和ObjectOutputStream类
- 有关ObjectInputStream和ObjectOutputStream性能
- ObjectOutputStream 和 ObjectInputStream的使用
- Java IO ObjectInputStream和ObjectOutputStream
- 对象流(ObjectOutputStream 和 ObjectInputStream)
- ObjectInputStream ObjectOutputStream
- ObjectInputStream ObjectOutputStream
- ObjectOutputStream/ObjectInputStream
- ObjectInputStream & ObjectOutputStream
- ObjectOutputStream/ObjectInputStream
- JAVA IO系列----ObjectInputStream和ObjectOutputStream类
- 反转字符串
- Java内部类
- poj3159--Candies(差分约束)
- 2015-华为招聘公开测试题目2-麻将番数
- 【阅读】《Head First javascript》第三章——探索客户端
- ObjectInputStream和ObjectOutputStream
- 【BZOJ】【P3632】【外太空旅行】【题解】【最大团】
- Convert Sorted List to Binary Search Tree 将有序链表转化为平衡二叉排序树
- const的思考
- 不同机具的通用的第二代居民身份证读写
- s3c2440的IIC控制
- USACO Longest Prefix
- ABAP:SMARTFORMS 之一:数据从程序中传送到Form中
- HDU 3722 Card Game(二分图最优匹配)