【问题标题】:Read whole file using XStream使用 XStream 读取整个文件
【发布时间】:2015-01-30 20:51:30
【问题描述】:

我想使用 XStream 读取 xml 文件的内容。我想读取整个文件,但不知道在while条件中放什么,这样XStream就不会抛出java.io.EOFException异常。基本上我想在到达文件末尾时停止循环。代码如下:

public static void main(String[] args) throws IOException, ClassNotFoundException
{
    XStream xstream = new XStream(new StaxDriver());
    xstream.alias("person", Person.class);
    Reader someReader = new FileReader("filename.xml");

    ObjectInputStream in = xstream.createObjectInputStream(someReader);

    while (???) {            
        Person a = (Person)in.readObject(); // Person is just a class containing a String and an int
        a.print();
    }
}

【问题讨论】:

    标签: java xml io


    【解决方案1】:

    我的建议:如果它们以列表形式存储在 XML 中,请尝试在 以列表形式读取它

    List<Person> people = new ArrayList<Person>();
    people = (List<Person>) xstream.fromXML(someReader);
    

    根据XStream APIXStream 对象可以从任意数量的不同输入中读取,包括直接从Reader 中读取。如果您确实直接从列表中读取,则需要稍微更改代码以允许隐式集合。可以在 here 找到使用隐式集合的一个很好的工作示例。

    或者,如果您确实想使用ObjectInputStream,您可以参考this questionthis answer,了解如何判断您何时到达ObjectInputStream 的末尾。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-19
      • 2013-12-21
      • 2012-09-22
      • 1970-01-01
      • 1970-01-01
      • 2014-05-18
      • 1970-01-01
      • 2013-12-12
      相关资源
      最近更新 更多