Java SFTP upload uses jsch, but how to overwrite the current file?

I tried to use jsch to upload two files to a server with SFTP If the directory is empty, uploading files works normally, but I want to upload the same files over and over again (just change the internal ID), but I can't figure out how to do this There are some static parameters in jsch called overwrite, but I can't find out how to use it

Anyone cares how I 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();
  }
}

Solution

I have never used jsch, but from its appearance, there are some overloaded put methods, one of which matches your current signature, adds a "mode" parameter, and seems to have 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);

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>