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

前端 未结 6 454
轻奢々
轻奢々 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-15 21:51

    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);
    }
    

提交回复
热议问题