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

rag*_*age 2 java sftp jsch

不幸的是,该getExitStatus()方法总是返回-1所以我不能用它来告诉我文件上传是否有效.我试图用getInputStream()的方法Channel类,但每当我试图从InputStream我的代码阻止永远读仿佛Channel实例还开着/连接(即使isConnectedisClosed()分别为虚假和真实的-这表明通道确实是封闭的) .我尝试从输入流中读取一个数据字节后,以下代码总是阻塞:

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

}

}
Run Code Online (Sandbox Code Playgroud)

我想我的问题是:

  1. 每当我尝试从输入流中读取时,为什么我的代码会阻塞(即使Channel它确实已关闭)

  2. 判断文件上传是否有效的方法是什么.我想如果抛出SFTPException不成功,否则我可以认为它是成功的?

Ken*_*ter 5

我想如果抛出SFTPException不成功,否则我可以认为它是成功的?

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

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

JCraft有一个示例程序,说明如何执行您可能觉得有用的SFTP.