使用 XStream 读取整个文件

Read whole file using XStream

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

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();
    }
}

我的建议:如果它们作为列表存储在 XML 中,请尝试在 中作为列表阅读它:

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

根据 XStream API, the XStream object can read from any number of different inputs, including directly from a Reader. If you do read in directly from a list, you will need to alter your code slightly to allow for implicit collections. A good working example of using implicit collections can be found here.

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