Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want to convert an output stream into String object

Tags:

java

jaxb

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

like image 889
TopCoder Avatar asked Mar 18 '10 17:03

TopCoder


People also ask

How do you write OutputStream to String?

Example: Convert OutputStream to String This is done using stream's write() method. Then, we simply convert the OutputStream to finalString using String 's constructor which takes byte array. For this, we use stream's toByteArray() method.

How do I change InputStream to String?

To convert an InputStream Object int to a String using this method. Instantiate the Scanner class by passing your InputStream object as parameter. Read each line from this Scanner using the nextLine() method and append it to a StringBuffer object. Finally convert the StringBuffer to String using the toString() method.

How do I get OutputStream content?

So you can get the OutputStream from that method as : OutputStream os = ClassName. decryptAsStream(inputStream,encryptionKey); And then use the os .


1 Answers

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

like image 174
Justin Gregoire Avatar answered Sep 23 '22 17:09

Justin Gregoire