0

I generate a XML like this. It works fine. But I want to print it out in Eliscps:

import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

public class PersonConstructor {
    String info="";
    String path="c://myfile/myperson";

    // here is my xml object
    Person person = new Person();
    person.setFirstName("fname");
    person.setLastName("lname");
    person.setTel("111-111-1111");
    person.setAddress("1000 main st.");

    //Serializer my object to file.
    Serializer serializer = new Persister();
    File file = new File(path);
    serializer.write(person, file);

    //now I want to print out my xml file.I don't know how to do it.
    info = file.toString();
    System.out.println(info);
}

Should I use output stream?

Andrew
  • 4,953
  • 15
  • 40
  • 58
SIYU TIAN
  • 3
  • 1
  • the serializer.write has an overload that accepts an outputStream. You could construct a ByteArrayOutputStream, have the serializer write to it, then construct a new string from the bytes like new String(myBAOS.getBytes()); then just print it. That will avoid disk IO entirely. – Mark W Sep 26 '14 at 18:32
  • possible duplicate of [How to pretty print XML from Java?](http://stackoverflow.com/questions/139076/how-to-pretty-print-xml-from-java) – Lorenzo Boccaccia Sep 26 '14 at 19:16
  • the code is: ' Serializer serializer = new Persister(); OutputStream os =new ByteArrayOutputStream(); serializer.write(person,os); info=os.toString();' return msg; – SIYU TIAN Sep 26 '14 at 20:25

1 Answers1

0

Use a buffered reader. Just make sure to either add the IOException to your method signature or surround with try/catch block.

BufferedReader in = new BufferedReader(new FileReader(file));
String line = in.readLine();
while(line != null)
{
    System.out.println(line);
    line = in.readLine();
}
in.close();
proulxs
  • 498
  • 2
  • 13