Java

Java Properties类的序列化

小樊
83
2024-08-23 23:25:31
栏目: 编程语言

Properties类是Java集合框架中的一种特殊类型,它表示一个持久的属性集。Properties类中的属性是以键值对的形式存储的,其中键和值都是字符串类型。

Properties类实现了Serializable接口,因此可以对其进行序列化操作。序列化是将对象转换为字节流的过程,可以将对象保存到文件或通过网络传输。

要对Properties对象进行序列化,可以使用ObjectOutputStream类将其写入到输出流中,示例如下:

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Properties;

public class PropertiesSerialization {
    public static void main(String[] args) {
        Properties properties = new Properties();
        properties.setProperty("key1", "value1");
        properties.setProperty("key2", "value2");

        try (FileOutputStream fileOut = new FileOutputStream("properties.ser");
             ObjectOutputStream objectOut = new ObjectOutputStream(fileOut)) {
            objectOut.writeObject(properties);
            System.out.println("Properties object serialized successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

在上面的示例中,首先创建了一个Properties对象,并为其添加了一些属性。然后使用ObjectOutputStream将Properties对象写入到名为"properties.ser"的文件中。

要反序列化Properties对象,可以使用ObjectInputStream类读取文件中的字节流,并将其转换为Properties对象,示例如下:

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.Properties;

public class PropertiesDeserialization {
    public static void main(String[] args) {
        Properties properties = null;

        try (FileInputStream fileIn = new FileInputStream("properties.ser");
             ObjectInputStream objectIn = new ObjectInputStream(fileIn)) {
            properties = (Properties) objectIn.readObject();
            System.out.println("Properties object deserialized successfully.");
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }

        if (properties != null) {
            System.out.println(properties.getProperty("key1"));
            System.out.println(properties.getProperty("key2"));
        }
    }
}

在上面的示例中,使用ObjectInputStream从"properties.ser"文件中读取字节流,并将其转换为Properties对象。最后打印出Properties对象中的属性值。

0
看了该问题的人还看了