Java
Chilkat2 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
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.SFtp;
public class ChilkatExample {
public static void main(String[] args) {
// Demonstrates the SFtp.CloseHandle method, which closes a remote file or directory handle. The
// only argument is the handle returned by OpenFile or OpenDir.
SFtp sftp = new SFtp();
// Connect, authenticate, and initialize the SFTP subsystem.
int port = 22;
try {
sftp.connect("sftp.example.com", port);
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
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";
String handle;
try {
sftp.authenticatePw("mySshLogin", password);
sftp.initializeSftp();
// Open a remote file, obtaining a handle.
handle = sftp.openFile("subdir/data.txt", "readOnly", "openExisting");
// ... use the handle ...
// Close the handle to release the server-side resource. A handle should not be used after it
// is closed.
sftp.closeHandle(handle);
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
System.out.println("Handle closed.");
sftp.disconnect();
}
}