ObjectInputStream & ObjectOutputStream

来源:互联网 发布:photoshop免费下载mac 编辑:程序博客网 时间:2024/05/21 00:14

ObjectInputStream & ObjectOutputStream用于读写java对象的高级流

ObjectInputStream:用于将字节数据读取后转换为java对象。对象反序列化过程。

ObjectOutputStream:用于将一个java中的对象转换为相应的字节并写出。对象序列化过程。

 

将基本类型数据转化为对应的字节序列---基本类型数据的序列化

将这些字节序列写入了文件进行长期保存---数据持久化

将字节序列转换为对应的基本类型数据---基本类型数据反序列化

 

序列化代码示例:

public class ObjectInputStreamDemo{         public static void main(String[] args) throws IOException,                        ClassNotFoundException        {                Point point = new Point(22, 33);                File file = new File("Object.obj");                writerPoint(point, file);                readPoint(file);        }         private static void writerPoint(Point point, File file) throws IOException        {                FileOutputStream fileOutputStream = new FileOutputStream(file);                ObjectOutputStream objectOutputStream = new ObjectOutputStream(                                fileOutputStream);                objectOutputStream.writeObject(point);                objectOutputStream.close();        }         private static void readPoint(File file) throws IOException,                        ClassNotFoundException        {                FileInputStream fileInputStream = new FileInputStream(file);                ObjectInputStream objectInputStream = new ObjectInputStream(                                fileInputStream);                Point point = (Point) objectInputStream.readObject();                System.out.println(point.toString());        } }

 

 

 /** * 序列化的类 */class Point implements Serializable{        private static final long serialVersionUID = 1L;         private int x;        private int y;         public Point()        {        }         public Point(int x, int y)        {                this.x = x;                this.y = y;        }         public int getX()        {                return x;        }         public void setX(int x)        {                this.x = x;        }         public int getY()        {                return y;        }         public void setY(int y)        {                this.y = y;        }         @Override        public String toString()        {                return "x = " + x + ", y = " + y;        }}

 

0 0
原创粉丝点击