Java 如何使用JSch判断SFTP上传是否成功

Java 如何使用JSch判断SFTP上传是否成功,java,sftp,jsch,Java,Sftp,Jsch,不幸的是,getExitStatus()方法总是返回-1,所以我不能用它来告诉我文件上传是否有效。我尝试使用Channel类的getInputStream()方法,但每当我尝试从inputstream读取时,我的代码总是被阻塞,就好像Channel实例仍然处于打开/连接状态一样(即使已连接和已关闭()分别为假和真-表明该频道确实已关闭)。在我尝试从输入流中读取一个字节的数据后,以下代码总是阻塞: public class Put { public static void main(String

不幸的是,
getExitStatus()
方法总是返回-1,所以我不能用它来告诉我文件上传是否有效。我尝试使用
Channel
类的
getInputStream()
方法,但每当我尝试从inputstream读取时,我的代码总是被阻塞,就好像
Channel
实例仍然处于打开/连接状态一样(即使
已连接
已关闭()
分别为假和真-表明该频道确实已关闭)。在我尝试从输入流中读取一个字节的数据后,以下代码总是阻塞:

public class Put {

public static void main(String[] args) throws IOException {

    Session session = null; 
    Channel channel = null; 
    ChannelSftp channelSftp = null; 
    InputStream in = null; 
    JSch jsch = new JSch();

    try {
        jsch.setKnownHosts("known_hosts");
        session = jsch.getSession("user", "host", 22);
        session.setPassword("password");

        session.connect();
        channel = session.openChannel("sftp");
        channel.setInputStream(null);
        stdout = channel.getInputStream();

        channel.connect();
        channelSftp = (ChannelSftp)channel;
        channelSftp.cd("/path/to/sftp");


        channelSftp.put("/path/to/localfile", "/path/to/remotefile");

    } catch (JSchException e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
    } catch (SftpException e) {
        System.out.println(e.id);
        System.out.println(e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {

        if(channelSftp != null && channelSftp.isConnected())channelSftp.exit();
        if(channel != null && channel.isConnected()) channel.disconnect();
        if(session != null && session.isConnected()) session.disconnect();
    }

    System.out.println("Channel is connected? " + channel.isConnected()); // returns false as i would expect
    System.out.println("Channel is closed? " + channel.isClosed()); // returns true as i would expect
    System.out.println(stdout.available()); // returns 0
    System.out.println(stdout.read()); // code blocks here

}

}
我想我的问题是:

  • 为什么每当我尝试从输入流读取时(即使
    通道确实已关闭),我的代码都会被阻塞

  • 如何判断文件上传是否有效。我猜如果抛出了一个SFTPException,它是不成功的,否则我可以假设它是成功的

  • 我猜如果抛出了一个SFTPException,它是不成功的,否则我可以假设它是成功的

    这是正确的。如果各种
    ChannelSftp.put()
    函数因任何原因失败,它们将抛出异常。如果要重复检查,可以在远程文件名上调用
    ChannelSftp.stat()
    …lstat()
    。但是请注意,在您有机会检查远程文件之前,另一个进程可能会假设删除或移动远程文件

    您通常不需要访问
    ChannelSftp
    的输入或输出流
    getExitStatus()
    将告诉您整个SFTP会话的退出状态,而不是特定操作的结果


    JCraft提供了您可能会发现有用的文件。

    如果该文件已经存在,但这次没有更新,该怎么办?“ChannelSftp.stat()”仍将返回正确状态,我们无法知道上载是否成功