pesho pesho -4 years ago 429
Java Question

Read whole file using XStream

I want to read the contents of a xml file using XStream. I want to read the whole file, but don't know what to put in the while condition, so that XStream doesn't throw a
exception.Basically I want to stop the cycle when I reach the end of the file. The code is below:

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

Answer Source

My recommendation: If they're stored as a list in the XML, try reading it in as a list:

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

According to the 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.

Alternately, if you do want to use an ObjectInputStream, you can refer to this question and this answer for solutions of how to tell when you've reached the end of an ObjectInputStream.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download