今天,我尝试使用 java.util.properties
存储一个 Object
。我看到很多示例只使用 String
或 Integer
。这是一个例子:
public static void main(String[] args) {
Properties prop = new Properties();
// add some properties
prop.setProperty("Height", "200");
prop.put("Width", "1500");
// print the list
System.out.println("" + prop);
try {
// store the properties list in an output stream
prop.store(System.out, "config.properties");
} catch (IOException ex) {
ex.printStackTrace();
}
}
那么是否可以将Object
存储在properties
文件或xml
文件中呢?
最佳答案
首先要存储一个对象,您应该将它序列化为一个字节数组,然后用 Base64 encoder 对其进行编码。 :
public static String toString(Object o) throws IOException {
try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);) {
oos.writeObject(o);
return new String(Base64Coder.encode(baos.toByteArray()));
}
}
然后就可以安全的存储到属性文件中了:
prop.put("object.instance", toString(o));
要从属性中读取对象,请使用此函数:
public static Object fromString(String s) throws IOException, ClassNotFoundException {
byte[] data = Base64Coder.decode(s);
Object o;
try (ObjectInputStream ois = new ObjectInputStream(
new ByteArrayInputStream(data))) {
o = ois.readObject();
}
return o;
}
您可以反序列化字符串中的对象:
Object o = fromString(prop.get("object.instance"));
关于java - 是否可以将对象存储到 Java 中的属性文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37795893/