Issue
I want to put a file to FTP address automatically in a scheduler.
I have a JSON object so I can create an XML from this.
I can create a xmlString
with a code below.
I want to put the XML in the xmlString
to a file abc.xml
at an FTP address. How I can do it?
private static String objToXml(Object object) throws JAXBException {
JAXBContext context = JAXBContext.newInstance(object.getClass());
Marshaller marshallerObj = context.createMarshaller();
marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
StringWriter sw = new StringWriter();
marshallerObj.marshal(object, sw);
return sw.toString();
}
String xmlString = "";
try {
xmlString = objToXml(anObject);
} catch (JAXBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Solution
If I understand your question correctly, you want to store a string to a file on an FTP server.
- Convert your string to an
InputStream
:
How do I convert a String to an InputStream in Java? - and then upload it:
Uploading byte array to FTP in Java
byte[] bytes = xmlString.getBytes(StandardCharsets.UTF_8);
InputStream inputStream = new ByteArrayInputStream(bytes);
ftpClient.storeFile(remotePath, inputStream);
Having that said, most XML libraries are be able to write directly to an OutputStream
, sparing the necessity (and memory waste) of the intermediate String
object.
Answered By - Martin Prikryl
Answer Checked By - Candace Johnson (JavaFixing Volunteer)