使用JSch上传Java SFTP,但如何覆盖当前文件? [英] Java SFTP upload using JSch, but how to overwrite the current file?

查看:466
本文介绍了使用JSch上传Java SFTP,但如何覆盖当前文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用JSch将两个文件上传到使用SFTP的服务器。如果目录为空,它可以正常上传文件,但我想反复上传相同的文件(只是更改内部的ID),但我无法弄清楚如何做到这一点。 JSch中有一些名为OVERWRITE的静态参数,但是我找不到如何使用它。

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?

这是我目前的代码:

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


推荐答案

我从来没有使用过JSch,但从外观上看,有一些重载的put方法,其中一个匹配你当前的签名,加上一个mode参数,并且在ChannelSftp类中似乎有三个静态模式参数(OVERWRITE = 0,RESUME = 1,APPEND = 2)所以你应该可以使用:

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

这篇关于使用JSch上传Java SFTP,但如何覆盖当前文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆