我用来XStream
在xml file
.
然后我再次反序列化文件以使用对象。
我的问题是,关闭程序后,xml“文件”消失了。那么如何将这个 xml 文件保存到特定目录呢?我已经尝试过FileOutputStream
,但它不起作用......我也用谷歌搜索,但没有找到适合我的解决方案......
方法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());
}
}
和方法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;
}
目录:\\releasearea\ToolReleaseArea\PersistenceSave
编辑
正确代码:(由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();
}
}
}
}