java 使用 XStream 保存 XML 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13063815/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 11:22:31  来源:igfitidea点击:

Save XML file with XStream

javaxstream

提问by Michael Schmidt

I use XStreamto 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 FileOutputStreambut it doesn't work... I also google it, but found not the right solution for me...

XStream过去常常在xml file.
然后我再次反序列化文件以使用对象。
我的问题是,在我关闭程序后,xml“文件”消失了。那么如何将这个 xml 文件保存到特定目录呢?我已经尝试过FileOutputStream但它不起作用......我也谷歌了它,但没有找到适合我的解决方案......

Method savePerson

方法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

和方法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

目录\\releasearea\ToolReleaseArea\PersistenceSave

EDIT
Correct Code: (by ppeterka)

编辑
正确的代码:(由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();
            }
        }
    }
}

回答by ppeterka

You didn't write the file, just obtained the serialized content...

你没有写文件,只是获得了序列化的内容......

FileOutputStream fos = null;
try {
    fos = new FileOutputStream("myfilename");
    fos.write("<?xml version=\"1.0\"?>".getBytes("UTF-8")); //write XML header, as XStream doesn't do that for us
    byte[] bytes = xml.getBytes("UTF-8");
    fos.write(bytes);

} catch(Exception e) {
    e.printStackTrace(); // this obviously needs to be refined.
} finally {
    if(fos!=null) {
        try{ 
            fos.close();
        } catch (IOException e) {
            e.printStackTrace(); // this obviously needs to be refined.
        }
    }
}

Also, your reading function has an error too: the xstream.fromXML(String)accepts a String, but it does not interpret it as a file name, but as the XML content itself... You have to use the fromXML(File)function:

此外,您的阅读功能也有一个错误:xstream.fromXML(String)接受 a String,但它不会将其解释为文件名,而是将其解释为 XML 内容本身...您必须使用该fromXML(File)功能:

public Person readPerson(String uNummer) {
    System.out.println("read person");
    Person person = new Person(); //if there is an error during deserialization, this is going to be returned, is this what you want?
    try{
        File xmlFile = new File(file_path + uNummer + ".xml");
        person = (Person) xstream.fromXML(xmlFile);       
    }catch(Exception e){
        System.err.println("Error in XML Read: " + e.getMessage());
    }
    return person;
}

回答by shazin

Use the overloaded method toXML(Object o, Writer w) to serialize directly to a file. The toXML method you are using doesn't save to a file.

使用重载方法 toXML(Object o, Writer w) 直接序列化到文件。您使用的 toXML 方法不会保存到文件中。

xstream.toXML(person, new FileWriter(file));

回答by Sembrano

Im doing like this is working well :

我这样做效果很好:

//Your Stream things...

    String xml = xstream.toXML(type);

        System.out.println(xml);

        BufferedReader reader = new BufferedReader(new StringReader(xml));
        BufferedWriter writer = new BufferedWriter(new FileWriter("test.xml",
                true));

        while ((xml = reader.readLine()) != null) {

            writer.write(xml + System.getProperty("line.separator"));

        }

        writer.close()

;

;

And output is :

输出是:

<type>
  <OBJECT__TYPE>sdfsdf</OBJECT__TYPE>
  <prop>
    <DESCRIPTION>hfh</DESCRIPTION>
    <PARENT>NULL</PARENT>
    <VIRTUAL>0</VIRTUAL>
    <VISIBLE>1</VISIBLE>
    <PICTURE>NULL</PICTURE>
    <HELP>345345</HELP>
    <MIN__NO>NULL</MIN__NO>
    <MAX__NO>1</MAX__NO>
    <NAME__FORMAT>NULL</NAME__FORMAT>
  </prop>
</type>
<type>
  <OBJECT__TYPE>test</OBJECT__TYPE>
  <prop>
    <DESCRIPTION>test</DESCRIPTION>
    <PARENT>NULL</PARENT>
    <VIRTUAL>0</VIRTUAL>
    <VISIBLE>0</VISIBLE>
    <PICTURE>NULL</PICTURE>
    <HELP>noe</HELP>
    <MIN__NO>NULL</MIN__NO>
    <MAX__NO>NULL</MAX__NO>
    <NAME__FORMAT>5475</NAME__FORMAT>
  </prop>
</type>