Stan Ostrovskii
Stan Ostrovskii

Reputation: 632

JSch not uploading complete file to remote SFTP server, only partial

I am trying to use the Jsch library to transfer a locally created XML file (marshalled from a Java object using JAXB) to a remote server. However, the file only gets partially uploaded. It is missing the end tag and an arbitrary amount of characters at the end.

My code looks like this (TradeLimits is a JAXB annotated Java class)

TradeLimits limits = getTradeLimits(); //complex object with many fields
JSch jsch = new JSch();
jschSession = jsch.getSession(username, remoteHost);

//to avoid unknown host issues
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
jschSession.setConfig(config);

jschSession.setPassword(password);
jschSession.setPort(22);
jschSession.connect();

ChannelSftp channelSftp = (ChannelSftp) jschSession.openChannel("sftp");
channelSftp.connect();

jaxbContext = JAXBContext.newInstance(TradeLimits.class);           
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); //for pretty print
marshaller.marshal(limits, channelSftp.put(limitUploadPathString)); //this uploads only partial xml file to sftp server
marshaller.marshal(limits, System.err)); //THIS WORKS CORRECTLY AND THE FULL XML IS PRINTED!        

channelSftp.disconnect();
channelSftp.exit();

Note how this cannot be a JAXB issue because it will print the complete XML elsewhere, but only partial is uploaded to remote server. What can possibly be the issue? Thanks in advance!

Upvotes: 0

Views: 1167

Answers (1)

jtahlborn
jtahlborn

Reputation: 53694

Always ensure you flush/close an OutputStream when you are done writing to it.

try(OutputSteam fileStream = channelSftp.put(limitUploadPathString)) {
  marshaller.marshal(limits, fileStream);
}

Upvotes: 2

Related Questions