Implementing SFTP Server Connection with Java Singleton Pattern
SFTP Server Connection Using Singleton Pattern in Java
The singleton design pattern ensures a class has only one instance while providing global access to that instance. This pattern is particularly useful for managign resources like SFTP server connections.
Singleton Implementation
import com.jcraft.jsch.*;
public class SftpConnector {
private static SftpConnector connector;
private Session session;
private SftpConnector() {
try {
JSch jsch = new JSch();
session = jsch.getSession("username", "hostname", 22);
session.setPassword("password");
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
} catch (JSchException e) {
e.printStackTrace();
}
}
public static synchronized SftpConnector getConnection() {
if (connector == null) {
connector = new SftpConnector();
}
return connector;
}
public Session getSession() {
return session;
}
}
File Transfer Operations
import com.jcraft.jsch.ChannelSftp;
public class SftpFileHandler {
public void upload(String localPath, String remotePath) {
try {
ChannelSftp channel = (ChannelSftp) SftpConnector
.getConnection()
.getSession()
.openChannel("sftp");
channel.connect();
channel.put(localPath, remotePath);
channel.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}