I want to convert an output stream into String object

JavaJaxb

Java Problem Overview


I want to convert an OutputStream into a String object. I am having an OutputStream object returned after marshalling the JAXB object.

Java Solutions


Solution 1 - Java

not very familiar with jaxb, from what i was able to find you can convert into a string using

public String asString(JAXBContext pContext, 
                        Object pObject)
                            throws 
                                JAXBException {
                                
    java.io.StringWriter sw = new StringWriter();
    
    Marshaller marshaller = pContext.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
    marshaller.marshal(pObject, sw);
    
    return sw.toString();
}

ws.apache.org

but I'm not sure about a stirng object. still searching.

** EDIT

> Marshalling a non-element > > Another common use case is where you > have an object that doesn't have > @XmlRootElement on it. JAXB allows you > to marshal it like this: > > marshaller.marshal( new JAXBElement(
> new > QName("","rootTag"),Point.class,new > Point(...))); > > This puts the element as the > root element, followed by the contents > of the object, then . You > can actually use it with a class that > has @XmlRootElement, and that simply > renames the root element name. > > At the first glance the second > Point.class parameter may look > redundant, but it's actually necessary > to determine if the marshaller will > produce (infamous) @xsi:type. In this > example, both the class and the > instance are Point, so you won't see > @xsi:type. But if they are different, > you'll see it. > > This can be also used to marshal a > simple object, like String or an > integer. > > marshaller.marshal( new JAXBElement(
> new > QName("","rootTag"),String.class,"foo > bar")); > > But unfortunately it cannot be used to > marshal objects like List or Map, as > they aren't handled as the first-class > citizen in the JAXB world.

found HERE

Solution 2 - Java

	StringWriter sw = new StringWriter();
    com.integra.xml.Integracao integracao = new Integracao();
    integracao.add(...);
try {
	JAXBContext context = JAXBContext.newInstance("com.integra.xml");
	Marshaller marshaller = context.createMarshaller();
	marshaller.marshal(integracao, sw );
	System.out.println(sw.toString());
} catch (JAXBException e) {
	e.printStackTrace();
}

Solution 3 - Java

public String readFile(String pathname) throws IOException {
    File file = new File(pathname);
    StringBuilder fileContents = new StringBuilder((int) file.length());
    Scanner scanner = new Scanner(file);
    String lineSeparator = System.getProperty("line.separator");

    try {
        while (scanner.hasNextLine()) {
            fileContents.append(scanner.nextLine() + lineSeparator);
        }
        return fileContents.toString();
    }
    finally {
        scanner.close();
    }
}    

Method to handle the XML and convert it to a string.

JAXBContext jc = JAXBContext.newInstance(ClassMatchingStartofXMLTags.class);
    Unmarshaller unmarshaller = jc.createUnmarshaller();
    //store filepath to be used
    String filePath = "YourXMLFile.xml";
    File xmlFile = new File(filePath);
    //Set up xml Marshaller
    ClassMatchingStartofXMLTags xmlMarshaller = (ClassMatchingStartofXMLTags) unmarshaller.unmarshal(xmlFileEdit);
    Marshaller marshaller = jc.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    // Use marshall to output the contents of the xml file
    System.out.println("Marshalled XML\n");
    marshaller.marshal(xmlMarshaller, System.out); 
    //Use Readfile method to convert the XML to a string and output the results
    System.out.println("\nXML to String");
    String strFile = ReadFile(xmlFile)
    System.out.println(strFile);     

Method within your class to get the XML and Marshall it Edit The above method will both output the marshalled xml and also the xml as a string.

Solution 4 - Java

Yes, there is a way to do it: just pass the String writer as input to it. So that it the xml created will be written to it

   public void saveSettings() throws IOException {
       FileOutputStream os = null;
       //Declare a StringWriter to which the output has to go
       StringWriter sw = new StringWriter();
       try {
           Answer ans1=new Answer(101,"java is a programming language","ravi");  
           Answer ans2=new Answer(102,"java is a platform","john");  
                      
           ArrayList<Answer> list=new ArrayList<Answer>();  
           list.add(ans1);  
           list.add(ans2);  
                      
           settings=new Question(1,"What is java?",list); 
           os = new FileOutputStream(FILE_NAME);
           this.marshaller.marshal(settings, new StreamResult(sw));
           System.out.println(sw.toString());
           new File(FILE_NAME).delete();
       } finally {
           if (os != null) {
               os.close();
           }
       }
   }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTopCoderView Question on Stackoverflow
Solution 1 - JavaJustin GregoireView Answer on Stackoverflow
Solution 2 - JavaRodrigo ValentimView Answer on Stackoverflow
Solution 3 - JavaStevie754View Answer on Stackoverflow
Solution 4 - JavaRajesh BView Answer on Stackoverflow