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

前端 未结 6 452
轻奢々
轻奢々 2020-12-15 21:42

Using JSch, is there a way to tell if a remote file exists without doing an ls and looping through the files to find a name match?

Thanks

6条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-15 21:58

    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://user@www.server.comm/path/to/some/random/folder/file.txt. I pass to function exists path as /path/to/some/random/folder/file.txt

提交回复
热议问题