I want to convert an OutputStream into a String object. I am having an OutputStream object returned after marshalling the JAXB object.
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.