Reading an XML file using FileInputStream (for Java)?

here's the deal.

For my project, I have to serialize and deserialize a random tree using Java and XStream. My teacher created Tree / RandomTree algorithms, so I don't need to worry about that. I don’t know how to do this: I use FileInputStream to read / write the XML file that I serialized and deserialized, but when I deserialized, I don’t know the method that was used to read the file. After I read the file, I would have to convert it from XML, and then print it as a string. Here is what I still have. (I imported everything correctly, just did not add it to my code segment).

FileInputStream fin; try { // Open an input stream fin = new FileInputStream ("/Users/Pat/programs/randomtree.xml"); //I don't know what to put below this, to read FileInpuStream object fin String dexml = (String)xstream.fromXML(fin); System.out.println(dexml); // Close our input stream fin.close(); System.out.println(dexml); // Close our input stream fin.close(); } // Catches any error conditions catch (IOException e) { System.err.println ("Unable to read from file"); System.exit(-1); } 

Edit: Hi guys, thanks for the help, I figured it out; I don’t think I need to print it as a string, I just needed to create a time comparison platform and so on, but thanks again!

+4
source share
2 answers

The xstream.fromXML() method will read from the input stream for you. I believe the problem is that you are returning the return value from xstream.fromXML(fin) to String when it should be passed to the type of the object you originally serialized ( RandomTree I assume). Thus, the code will look like this:

 RandomTree tree = (RandomTree)xstream.fromXML(fin); 

EDIT: After clarification in the comments, the author’s goal is to read in String first so that the XML content can be printed before deserialization. To this end, I recommend taking a look at the IOUtils library mentioned in this thread.

+1
source

From what I understand from http://x-stream.imtqy.com/tutorial.html (I had never worked with XStream before), you first need to define your types. Casting for String is definitely wrong, you probably need an individual type (depending on what's inside your random XML), then you need to map the XML tags to your members:

eg.

 xstream.alias("person", Person.class); xstream.alias("phonenumber", PhoneNumber.class); 

means that it matches the "person" tag inside your XML with your Person class.

For derserialize you can:

 RandomTree myRandomTree = (RandomTree)xstream.fromXML( xml ); 

In addition, you close your thread twice, and you probably want to do this in the finally block :)

Edit: by reading your comment above ...

Your task consists of two steps:

  • Deserialization
  • Serialization

To serialize your object, you must first deserialize it from your input file.

To output your object as a string, simply do

 String xml = xstream.toXML( myRandomTree ); 
+1
source

All Articles