Use below code snippet to validate XML payload and write payload content to a file in local system.
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileOutputStream;
import javax.xml.parsers.DocumentBuilderFactory;
public class WriteXMLToFile {
public static void main(String[] args) {
String localFileName = "<file path and file name to Store XML payload>";
boolean xmlValidated = false;
String xmlPayload = "<XML Payload>";
try {
DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(xmlPayload.getBytes()));
xmlValidated = true;
} catch (Exception ex) {
System.out.println("Error while validating XML " + ex);
}
if (xmlValidated) {
try {
FileOutputStream fileOutputStream = new FileOutputStream(new File(localFileName));
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
bufferedOutputStream.write(xmlPayload.getBytes());
}
catch (FileNotFoundException fnfe) {
System.out.println("Specified file not found " + fnfe);
} catch (IOException ioe) {
System.out.println("Error while writing file " + ioe);
} finally {
if (bufferedOutputStream != null) {
try {
bufferedOutputStream.flush();
bufferedOutputStream.close();
} catch (Exception e) {
System.out.println("Error while closing stream " + e);
}
}
}
} else {
System.out.println("XML payload is not valid");
}
}
}
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileOutputStream;
import javax.xml.parsers.DocumentBuilderFactory;
public class WriteXMLToFile {
public static void main(String[] args) {
String localFileName = "<file path and file name to Store XML payload>";
boolean xmlValidated = false;
String xmlPayload = "<XML Payload>";
try {
DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(xmlPayload.getBytes()));
xmlValidated = true;
} catch (Exception ex) {
System.out.println("Error while validating XML " + ex);
}
if (xmlValidated) {
try {
FileOutputStream fileOutputStream = new FileOutputStream(new File(localFileName));
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
bufferedOutputStream.write(xmlPayload.getBytes());
}
catch (FileNotFoundException fnfe) {
System.out.println("Specified file not found " + fnfe);
} catch (IOException ioe) {
System.out.println("Error while writing file " + ioe);
} finally {
if (bufferedOutputStream != null) {
try {
bufferedOutputStream.flush();
bufferedOutputStream.close();
} catch (Exception e) {
System.out.println("Error while closing stream " + e);
}
}
}
} else {
System.out.println("XML payload is not valid");
}
}
}