abi*_*964 14
这是我在JSch中检查目录存在的方式.
注意:与此问题无关,但有些人可能会发现它很有用.
如果dir不存在,则创建目录
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);
}
Run Code Online (Sandbox Code Playgroud)
zel*_*nka 10
你也可以这样做:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
如果对不存在的东西执行lstat,则会获得id为2的SftpExecption,否则您将获得有关该文件的信息.
实际上在我的项目中ls没有循环工作。我只是传递给ls带有文件名的调用路径。
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();
}
Run Code Online (Sandbox Code Playgroud)
例如,存在一个file.txt带有url 的文件sftp://user@www.server.comm/path/to/some/random/folder/file.txt。我通过exists path作为/path/to/some/random/folder/file.txt
(这是如果您使用库的 SFTP 部分,这是我没有考虑的假设。)
我认为它ls(String path)会接受文件名;我暂时无法检查。
如果没有,则无需手动迭代;您可以使用选择器变体:
ls(String path, ChannelSftp.LsEntrySelector selector)
Run Code Online (Sandbox Code Playgroud)