Reputation: 1632
Today I try to store an Object
using java.util.properties
. I see many example just use String
or Integer
. Here is an example:
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();
}
}
So is it possible to store an Object
in properties
file or xml
file?
Upvotes: 4
Views: 10426
Reputation: 44965
No as it is stated into the Javadoc:
If the store or save method is called on a "compromised" Properties object that contains a non-String key or value, the call will fail.
If you really need to store your object into a Properties
you could convert it into JSON
as it is a well known format that is readable by a human being such that if someone adds wrong characters in the middle you can still fix it.
Here is how you could do it using ObjectMapper
:
Properties prop = new Properties();
ObjectMapper mapper = new ObjectMapper();
// Convert my object foo into JSON format and put it into my Properties object
prop.put("myObj", mapper.writeValueAsString(foo));
StringWriter output = new StringWriter();
// Store my properties
prop.store(output, null);
prop = new Properties();
// Load my properties
prop.load(new StringReader(output.toString()));
// Parse my object foo from the value of my new Properties object
Foo foo2 = mapper.readValue(prop.getProperty("myObj"), Foo.class);
Here is a good tutorial that explains how you can use ObjectMapper
in more details.
Upvotes: 2
Reputation: 426
To store an object at first you should serialize it to a byte array then encode it with a 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()));
}
}
Then you can store it safely to the property file:
prop.put("object.instance", toString(o));
To read the object from the properties, use this function:
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;
}
You can deserialize the object from the string:
Object o = fromString(prop.get("object.instance"));
Upvotes: 4