在 Java 中将 XML 文件(使用 XStream)写入文件系统

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/335374/
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-08-11 13:35:15  来源:igfitidea点击:

Write XML file (using XStream) to filesystem in Java

javaxmlserialization

提问by ParseTheData

I need to be able to serialize a string and then have it save in a .txt or .xml file. I've never used the implementation to read/write files, just remember I am a relative beginner. Also, I need to know how to deserialize the string to be printed out in terminal as a normal string.

我需要能够序列化一个字符串,然后将其保存在 .txt 或 .xml 文件中。我从未使用该实现来读/写文件,请记住我是一个相对初学者。另外,我需要知道如何将要在终端中打印出的字符串反序列化为普通字符串。

回答by jsight

Is there any particular reason to use XStream? This would be extremely easy to do with something like JDOMif all you are doing is trying to serialize a string or two.

使用 XStream 有什么特别的理由吗?如果您所做的只是尝试序列化一两个字符串,那么使用JDOM 之类的东西就非常容易做到这一点。

Ie, something like: Document doc = new Document();

即,类似于:Document doc = new Document();

Element rootEl = new Element("root");
rootEl.setText("my string");
doc.appendChild(rootEl);
XMLOutputter outputter = new XMLOutputter();
outputter.output(doc);

Some of the details above are probably wrong, but thats the basic flow. Perhaps you should ask a more specific question so that we can understand exactly what problem it is that you are having?

上面的一些细节可能是错误的,但这是基本流程。也许您应该问一个更具体的问题,以便我们能够准确了解您遇到的问题是什么?

回答by Alex Beardsley

From http://www.xml.com/pub/a/2004/08/18/xstream.html:

http://www.xml.com/pub/a/2004/08/18/xstream.html

import com.thoughtworks.xstream.XStream;

class Date {
    int year;
    int month;
    int day;
}

public class Serialize {
    public static void main(String[] args) {

        XStream xstream = new XStream();

        Date date = new Date();
        date.year = 2004;
        date.month = 8;
        date.day = 15;

        xstream.alias("date", Date.class);

        String decl = "\n";

        String xml = xstream.toXML(date);

        System.out.print(decl + xml);
    }
}

public class Deserialize {

    public static void main(String[] args) {

        XStream xstream = new XStream();

        Date date = new Date();

        xstream.alias("date", Date.class);

        String xml = xstream.toXML(date);

        System.out.print(xml);

        Date newdate = (Date)xstream.fromXML(xml);
        newdate.month = 12;
        newdate.day = 2;

        String newxml = xstream.toXML(newdate);

        System.out.print("\n\n" + newxml);
    }
}

You can then take the xml string and write it to a file.

然后,您可以获取 xml 字符串并将其写入文件。

回答by James

If you can serialize it to a txt file, just open an ObjectOutputStream and have it use String's own serialization capability for you.

如果您可以将其序列化为 txt 文件,只需打开一个 ObjectOutputStream 并让它为您使用 String 自己的序列化功能。

String str = "serialize me";
    String file = "file.txt";
    try{
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(file));
        out.writeObject(str);
        out.close();

        ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
        String newString = (String) in.readObject();
        assert str.equals(newString);
        System.out.println("Strings are equal");
    }catch(IOException ex){
        ex.printStackTrace();
    }catch(ClassNotFoundException ex){
        ex.printStackTrace();
    }

You could also just open a PrintStream and syphon it out that way, then use a BufferedReader and readLine(). If you really want to get fancy (since this is a HW assignment after all), you could use a for loop and print each character individually. Using XML is more complicated than you need to serialize a String and using an external library is just overkill.

您也可以只打开 PrintStream 并以这种方式将其吸出,然后使用 BufferedReader 和 readLine()。如果你真的想花哨(因为这毕竟是一个硬件分配),你可以使用 for 循环并单独打印每个字符。使用 XML 比序列化字符串更复杂,使用外部库只是过度。

回答by James

XStream has facilities to read from and write to files, see the simple examples (Writer.java and Reader.java) in this article.

XStream的有设施,读取和写入文件,看到简单的例子(Writer.java和Reader.java)在这篇文章中

回答by Piko

If you need to create a text file containing XML that represents the contents of an object (and make it bidirectional), just use JSON-lib:

如果您需要创建一个包含表示对象内容的 XML 的文本文件(并使其双向),只需使用 JSON-lib:

class MyBean{  
   private String name = "json";  
   private int pojoId = 1;  
   private char[] options = new char[]{'a','f'};  
   private String func1 = "function(i){ return this.options[i]; }";  
   private JSONFunction func2 = new JSONFunction(new String[]{"i"},"return this.options[i];");  

   // getters & setters  
   ...  
}  

JSONObject jsonObject = JSONObject.fromObject( new MyBean() );
String xmlText = XMLSerializer.write( jsonObject );

From there just wrote the String to your file. Much simpler than all those XML API's. Now, however, if you need to conform to a DTD or XSD, this is a bad way to go as it's much more free-format and conforms only to the object layout.

从那里刚刚将字符串写入您的文件。比所有那些 XML API 简单得多。但是,现在,如果您需要符合 DTD 或 XSD,这是一种糟糕的方法,因为它的格式更加自由并且仅符合对象布局。

http://json-lib.sourceforge.net/usage.html

http://json-lib.sourceforge.net/usage.html

Piko

皮科

回答by prule

If you are beginning Java, then take some time to look through the Apache Commons project. There are lots of basic extensions to java that you will make use of many times.

如果您刚开始接触 Java,请花一些时间浏览 Apache Commons 项目。您将多次使用 Java 的许多基本扩展。

I'm assuming you just want to persist a string so you can read it back later - in which case it doesn't necessarily need to be XML.

我假设您只想保留一个字符串,以便您可以稍后读回它 - 在这种情况下,它不一定需要是 XML。

To write a string to a file, see org.apache.commons.io.FileUtils:

要将字符串写入文件,请参阅 org.apache.commons.io.FileUtils:

FileUtils.writeStringToFile(File file,String data)

FileUtils.writeStringToFile(File file,String data)

To read it back:

读回来:

FileUtils.readFileToString(File file)

FileUtils.readFileToString(File file)

References:

参考:

http://commons.apache.org/

http://commons.apache.org/

http://commons.apache.org/io

http://commons.apache.org/io

http://commons.apache.org/io/api-release/org/apache/commons/io/FileUtils.html

http://commons.apache.org/io/api-release/org/apache/commons/io/FileUtils.html

Make sure you also look at commons-langfor lots of good basic stuff.

确保您还查看commons-lang以获取许多好的基本内容。

回答by yeforriak

try something like this:

尝试这样的事情:

    FileOutputStream fos = null;
    try {
        new File(FILE_LOCATION_DIRECTORY).mkdirs();
        File fileLocation = new File(FILE_LOCATION_DIRECTORY + "/" + fileName);
        fos = new FileOutputStream(fileLocation);
        stream.toXML(userAlertSubscription, fos);                
    } catch (IOException e) {
        Log.error(this, "Error %s in file %s", e.getMessage(), fileName);
    } finally {
        IOUtils.closeQuietly(fos);
    }