Java提供了将对象以字节的形式写入到磁盘中,在需要的时候在从磁盘中恢复的功能,在网络传输中非常有用,下面将代码贴上,分别用两种形式实现了对象的序列化,其中第二种当时能将指定的变量序列化,更加人性化的随心所欲
- package com.bird.thinking;
-
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.ObjectInputStream;
- import java.io.ObjectOutputStream;
- import java.io.Serializable;
-
-
-
-
-
- public class Data {
- public static void writeObject() throws Exception{
- Worm worm = new Worm("Bird");
- ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("d://worm.out"));
- out.writeObject(worm);
- out.close();
- }
-
-
- public static void readObject() throws Exception{
- ObjectInputStream in = new ObjectInputStream(new FileInputStream("d://worm.out"));
- Worm s2 = (Worm) in.readObject();
- System.out.println(s2);
- }
-
- public static void main(String[] args) throws Exception{
-
- readObject();
- }
- }
-
-
- class Worm implements Serializable{
-
- private static final long serialVersionUID = 1L;
- private String name = null;
- public Worm(String name){
- this.name = name;
- }
-
- public String toString(){
- return name;
- }
- }
|