Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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();
  }
}
like image 654
Sebastian L Avatar asked Jul 04 '13 14:07

Sebastian L


1 Answers

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);

like image 51
Hyddan Avatar answered Oct 04 '22 22:10

Hyddan