Check whether the path exists on server or not in Java

岁酱吖の 提交于 2021-02-09 11:52:10

问题


I am creating a Java program in which I am uploading file to server on a particular path. I am using jSch for sftp.

So, before uploading the file, I want to check if the given directory exists on server or not.

if(path exists)
    //upload file to the location
else
    //create the directory and then upload the file.

How do I check the path exists or not?

Note: I am executing the code on a client that will check for the existence of a remote directory on a server. So please don't suggest File.exists().


回答1:


Reading the Documentation for ChannelSftp it would appear you can just lstat the directory:

SftpATTRS attrs = channelSftp.lstat(path);

If that throws an exception, it doesn't exist. You can then use channelSftp.mkdir(path) to create it.




回答2:


I am not familiar with this library, but from this example code: http://www.jcraft.com/jsch/examples/Sftp.java.html it looks like you can use

ChannelSftp c = ..;
c.ls('<path>')

to retrieve the file, this should tell you whether it exists or not.



来源:https://stackoverflow.com/questions/21276775/check-whether-the-path-exists-on-server-or-not-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!