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

时光毁灭记忆、已成空白 提交于 2019-12-03 11:19:26

问题


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

回答1:


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



来源:https://stackoverflow.com/questions/17473398/java-sftp-upload-using-jsch-but-how-to-overwrite-the-current-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!