title: A simple way to verify the existence of a file on the SFTP server in Java
body: <p>I am writing an SFTP client using the <a href="https://github.com/apache/mina-sshd" rel="nofollow noreferrer">Apache Mina SSHD library</a>, specifically <code>sshd-sftp 2.3.0</code>. I chose it instead of the <a href="https://github.com/hierynomus/sshj" rel="nofollow noreferrer">SSHJ library</a>, because it is possible to write a <code>String</code> to a remote file directly, and there are also no unnecessary dependencies.</p>
  
  <p>The task: when sending files to the SFTP server to make a backup copy of the previous file, if any.</p>
  
  <p>I studied all the possibilities that the <code>SftpClient</code> class provides, and among them I did not find an easy way to search for a file.</p>
  
  <ul>
  <li>There are <code>listDir</code> and <code>readDir</code> methods, they return <code>Iterable &lt;DirEntry&gt;</code>, but I suspect that with a large number of files they will work slowly.</li>
  <li>We can simply force a file to be renamed using the <code>rename</code> method, but in my case there can be many backup files, and we must first find a free file name.</li>
  </ul>
  
  <p>The current solution is to get the state of the file. If there is no such file, then a <code>SftpException</code> will be thrown, for example, "SFTP error (SSH_FX_NO_SUCH_FILE): No such file or directory". This message can be analyzed, and if the file is really not found, then just don't throw this exception further. Here is the code:</p>
  
  <pre class="lang-java prettyprint-override"><code>    private boolean fileExists(SftpClient sftpClient, String remoteDest) throws IOException {
          try {
              return null != sftpClient.stat(remoteDest);
          } catch (SftpException e) {
              if (e.getStatus() != SftpConstants.SSH_FX_NO_SUCH_FILE) {
                  LOGGER.error("Error finding file {}", remoteDest);
                  throw e;
              }
              return false;
          }
      }
  </code></pre>
  
  <p>The main problem is that this solution is ugly. </p>
  
  <p>However, on the Internet I found only similar solutions using libraries <a href="https://www.programcreek.com/java-api-examples/?class=com.jcraft.jsch.ChannelSftp&amp;method=SSH_FX_NO_SUCH_FILE" rel="nofollow noreferrer">JSch</a> and <a href="https://www.programcreek.com/java-api-examples/?api=com.trilead.ssh2.SFTPv3FileAttributes" rel="nofollow noreferrer">Trilead SSH-2 for Java</a>.</p>
  
  <p>Perhaps there is another, simpler and more competent way to check for a file on an SFTP server?</p>