可序列化是什么意思?

SerializableJava中的类对什么意味着什么?或者总的来说...



小唯快跑啊
浏览 1232回答 3
3回答

倚天杖

虽然大多数用户已经给出了答案,但是我想为需要它的人添加一个示例,以解释这个想法:假设您有一个像以下这样的班级人员:public class Person implements java.io.Serializable {    /**     *      */    private static final long serialVersionUID = 1L;    public String firstName;    public String lastName;    public int age;    public String address;    public void play() {        System.out.println(String.format(                "If I win, send me the trophy to this address: %s", address));    }    @Override    public String toString() {        return String.format(".....Person......\nFirst Name = %s\nLast Name = %s", firstName, lastName);    }}然后创建一个像这样的对象:Person william = new Person();        william.firstName = "William";        william.lastName = "Kinaan";        william.age = 26;        william.address = "Lisbon, Portugal";您可以将该对象序列化为许多流。我将对两个流执行此操作:序列化到标准输出:public static void serializeToStandardOutput(Person person)            throws IOException {        OutputStream outStream = System.out;        ObjectOutputStream stdObjectOut = new ObjectOutputStream(outStream);        stdObjectOut.writeObject(person);        stdObjectOut.close();        outStream.close();    }序列化到文件:public static void serializeToFile(Person person) throws IOException {        OutputStream outStream = new FileOutputStream("person.ser");        ObjectOutputStream fileObjectOut = new ObjectOutputStream(outStream);        fileObjectOut.writeObject(person);        fileObjectOut.close();        outStream.close();    }然后:从文件反序列化:public static void deserializeFromFile() throws IOException,            ClassNotFoundException {        InputStream inStream = new FileInputStream("person.ser");        ObjectInputStream fileObjectIn = new ObjectInputStream(inStream);        Person person = (Person) fileObjectIn.readObject();        System.out.println(person);        fileObjectIn.close();        inStream.close();    }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java