I use XStream to write an object in a xml file.
Then I deserializing the file again to use the objects.
My Problem is, that after I close my program, the xml “file” is gone. So how can I save this xml file to a specific directory? I already tried FileOutputStream but it doesn’t work… I also google it, but found not the right solution for me…
Method savePerson
public void savePerson(String uNummer, Person person) {
System.out.println("save person");
try{
xml = xstream.toXML(person);
}catch (Exception e){
System.err.println("Error in XML Write: " + e.getMessage());
}
}
And the Method readPerson
public Person readPerson(String uNummer) {
System.out.println("read person");
Person person = new Person();
try{
person = (Person) xstream.fromXML(file_path + uNummer + ".xml");
}catch(Exception e){
System.err.println("Error in XML Read: " + e.getMessage());
}
return person;
}
Directory: \\releasearea\ToolReleaseArea\PersistenceSave
EDIT
Correct Code: (by ppeterka)
public void savePerson(String uNummer, Person person) {
System.out.println("save person XML");
FileOutputStream fos = null;
try{
xml = xstream.toXML(person);
fos = new FileOutputStream(file_path + uNummer + ".xml");
fos.write("<?xml version=\"1.0\"?>".getBytes("UTF-8"));
byte[] bytes = xml.getBytes("UTF-8");
fos.write(bytes);
}catch (Exception e){
System.err.println("Error in XML Write: " + e.getMessage());
}
finally{
if(fos != null){
try{
fos.close();
}catch (IOException e) {
e.printStackTrace();
}
}
}
}
You didn’t write the file, just obtained the serialized content…
Also, your reading function has an error too: the
xstream.fromXML(String)accepts aString, but it does not interpret it as a file name, but as the XML content itself… You have to use thefromXML(File)function: