Java SFTP upload using JSch, but how to overwrite the current file?

Sebastian L picture Sebastian L · Jul 4, 2013 · Viewed 42.8k times · Source

I am trying to upload two files to a server with SFTP using JSch. It works fine to upload the files if the directory is empty but I want to upload the same file over and over (just changing an id inside) but I can't figure out how to do this. There is some static parameter in JSch called OVERWRITE but I can't find out how to use it.

Anyone care to show me how I should add this setting?

This is my current code:

public void upload() {
  try {
    JSch jsch = new JSch();
session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
session.setPassword(SFTPPASS);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
channel = session.openChannel("sftp");
channel.connect();
channelSftp = (ChannelSftp) channel;
channelSftp.cd(SFTPWORKINGDIR);

    File f1 = new File("ext_files/" + FILETOTRANSFER1);
channelSftp.put(new FileInputStream(f1), f1.getName());
File f2 = new File("ext_files/" + FILETOTRANSFER2);
channelSftp.put(new FileInputStream(f2), f2.getName());

channelSftp.exit();
session.disconnect();
} catch (Exception ex) {
  ex.printStackTrace();
  }
}

Answer

Hyddan picture Hyddan · Jul 4, 2013

I've never used JSch but from the looks of it there are a number of overloaded put methods where one matches your current signature with the addition of a "mode" parameter and there seems to be three static mode parameters in the ChannelSftp class (OVERWRITE = 0, RESUME = 1, APPEND = 2) so you should be able to use:

channelSftp.put(new FileInputStream(f1), f1.getName(), ChannelSftp.OVERWRITE);