Using JSch, is there a way to tell if a remote file exists without doing an ls?

You can also do something like this:

try {
    channelSftp.lstat(name);
} catch (SftpException e){
    if(e.id == ChannelSftp.SSH_FX_NO_SUCH_FILE){
    // file doesn't exist
    } else {
    // something else went wrong
        throw e;
    }
}

If you do an lstat on something that doesn’t exist you get an SftpExecption with an id of 2, otherwise you get information about the file.

Leave a Comment