Sample code for 30+ languages & platforms
Java

Close a Remote SFTP File or Directory Handle

See more SFTP Examples

Demonstrates the Chilkat SFtp.CloseHandle method, which closes a remote file or directory handle previously returned by OpenFile or OpenDir. The only argument is the handle.

Background: Every opened handle corresponds to state the server holds, and servers cap how many a session may keep open at once, so a long-running program that forgets to close handles will eventually start failing to open new ones. Closing also ensures buffered writes are committed. Once closed, a handle is invalid and must not be reused.

Chilkat Java Downloads

Java
import com.chilkatsoft.*;

public class ChilkatExample {

  static {
    try {
        System.loadLibrary("chilkat");
    } catch (UnsatisfiedLinkError e) {
      System.err.println("Native code library failed to load.\n" + e);
      System.exit(1);
    }
  }

  public static void main(String argv[])
  {
    boolean success = false;

    //  Demonstrates the SFtp.CloseHandle method, which closes a remote file or directory handle.  The
    //  only argument is the handle returned by OpenFile or OpenDir.

    CkSFtp sftp = new CkSFtp();

    //  Connect, authenticate, and initialize the SFTP subsystem.
    int port = 22;
    success = sftp.Connect("sftp.example.com",port);
    if (success == false) {
        System.out.println(sftp.lastErrorText());
        return;
        }

    //  Normally you would not hard-code the password in source.  You should instead obtain it
    //  from an interactive prompt, environment variable, or a secrets vault.
    String password = "mySshPassword";

    success = sftp.AuthenticatePw("mySshLogin",password);
    if (success == false) {
        System.out.println(sftp.lastErrorText());
        return;
        }

    success = sftp.InitializeSftp();
    if (success == false) {
        System.out.println(sftp.lastErrorText());
        return;
        }

    //  Open a remote file, obtaining a handle.
    String handle = sftp.openFile("subdir/data.txt","readOnly","openExisting");
    if (sftp.get_LastMethodSuccess() == false) {
        System.out.println(sftp.lastErrorText());
        return;
        }

    //  ... use the handle ...

    //  Close the handle to release the server-side resource.  A handle should not be used after it
    //  is closed.
    success = sftp.CloseHandle(handle);
    if (success == false) {
        System.out.println(sftp.lastErrorText());
        return;
        }

    System.out.println("Handle closed.");

    sftp.Disconnect();
  }
}