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.


This is how I check directory existence in JSch.

Note: not related to this question, but some may find it useful.

Create directory if dir does not exist

ChannelSftp channelSftp = (ChannelSftp)channel;
String currentDirectory=channelSftp.pwd();
String dir="abc";
SftpATTRS attrs=null;
try {
    attrs = channelSftp.stat(currentDirectory+"/"+dir);
} catch (Exception e) {
    System.out.println(currentDirectory+"/"+dir+" not found");
}

if (attrs != null) {
    System.out.println("Directory exists IsDir="+attrs.isDir());
} else {
    System.out.println("Creating dir "+dir);
    channelSftp.mkdir(dir);
}

Actually in my project ls working without loops. I just pass to the ls call path with filename.

private static boolean exists(ChannelSftp channelSftp, String path) {
    Vector res = null;
    try {
        res = channelSftp.ls(path);
    } catch (SftpException e) {
        if (e.id == SSH_FX_NO_SUCH_FILE) {
            return false;
        }
        log.error("Unexpected exception during ls files on sftp: [{}:{}]", e.id, e.getMessage());
    }
    return res != null && !res.isEmpty();
}

For example there a file file.txt with an url sftp://[email protected]/path/to/some/random/folder/file.txt. I pass to function exists path as /path/to/some/random/folder/file.txt

Tags:

Java

Jsch