Search code examples
javaspring-bootdomsftp

Saving DOMSource object created into a folder in SFTP Server in Java


I need to save the newly created DOMSource object as new XML file into a folder inside the SFTP server (not transferring a file from local computer into SFTP).

Here is the code

public void save(String xmlFilePath, Document document) {

    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
    transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "");
    Transformer transformer;
    try {
        transformer = transformerFactory.newTransformer();
        DOMSource domSource = new DOMSource(document);
        StreamResult streamResult = new StreamResult(new File(xmlFilePath));
        transformer.transform(domSource,streamResult);

    } catch (TransformerException | NullPointerException e) {
        e.printStackTrace();
    }
}

Solution

  • Use JSch SSH/SFTP library.

    1. Afaik, it's the most widely used SFTP library for Java

    2. It supports uploading data from streams.

      I assume that its ChannelSftp.put overload that returns OutputStream can be hooked to your StreamResult (instead of the File).

      StreamResult streamResult =
          new StreamResult(channelSftp.put("/sftp/path/file.zml"));