SFTP File Upload and Download Using Java
Uploading file to SFTP server is common task for the java developers.There are many ways to upload local file to remote SFtP server like using JSch, SSHJ, and Apache Commons VFS.We will try them one by one.
Using JSch
Using Apache Commons VFS
Using SSHJ
Using JSch
We have maven dependency
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>
There are two ways to user the JSch.
a). Using Password Authentication
b). Private Key Authentication
We see both of them.
a). Using Password Authentication
In the Password Authentication, we need to pass username and password to JSH client along with host and port.
public static Session getSFTPSession(String userName,String password,int port, String host)
throws SftpException, JSchException {
Session session = null;
System.out.println("SFTPEngine getDASSftpSession():port- " + port
+ " , host- " + host + " , userName- " + userName);
session = jsch.getSession(userName, host, port);
UserInfo ui = new MyUserInfo();
session.setPassword(SFTPPASS);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
session.setUserInfo(ui);
sftpSession = session;
return sftpSession;
}
public void sendFileToSFTPServer(String fileName) {
String destFtpFolder = "tempFolder";
Channel channel = null;
ChannelSftp channelSftp = null;
System.out.println("preparing the host information for sftp.");
try {
Session session = getSFTPSession("userName","password" 22,"host");
System.out.println("Host connected.");
channel = session.openChannel("sftp");
channel.connect();
System.out.println("sftp channel opened and connected.");
channelSftp = (ChannelSftp) channel;
channelSftp.cd(SFTPWORKINGDIR);
File f = new File(fileName);
fChannel.cd(destFtpFolder);// mkdir if folder not exist
File srcFile = new File(fileName);
logger.info("*****pwd**** : "+fChannel.pwd());
fChannel.cd(destFtpFolder);
FileInputStream inputStream = new FileInputStream(srcFile);
fChannel.put(inputStream, srcFile.getName());
inputStream.close();
log.info("File transfered successfully to host.");
} catch (Exception ex) {
System.out.println("Exception found while tranfer the response.");
} finally {
channelSftp.exit();
System.out.println("sftp Channel exited.");
channel.disconnect();
System.out.println("Channel disconnected.");
session.disconnect();
System.out.println("Host Session disconnected.");
}
}
b). Private Key Authentication
In the Public Key Authentication we need to add code to add private key.as
JSch jsch = new JSch();
jsch.addIdentity((new File(privateKey)).getAbsolutePath(), "");
public boolean connectTopSFTPUsingKey(String privateKey, int port, String host,
String userName) throws Exception {
private ChannelSftp fChannel = null;
jsch = new JSch();
jsch.addIdentity((new File(privateKey)).getAbsolutePath(), "");
Session session = getSFTPKeyBaseSession("privateKeyPath",22, "host",
"userName")
if (fChannel == null || !fChannel.isConnected()) {
com.jcraft.jsch.Channel channel = session
.openChannel("sftp");
channel.connect();
fChannel = (ChannelSftp) channel;
}
} else {
if (fChannel == null || !fChannel.isConnected()) {
com.jcraft.jsch.Channel channel = session
.openChannel("sftp");
channel.connect();
fChannel = (ChannelSftp) channel;
}
}
public static Session getSFTPKeyBaseSession(String privateKey, int port, String host,
String userName) throws Exception {
Session session = null;
JSch jsch = new JSch();
jsch.addIdentity((new File(privateKey)).getAbsolutePath(), "");
session = jsch.getSession(userName, host, port);
UserInfo ui = new MyUserInfo();
session.setUserInfo(ui);
session.connect();
return session;
}
We have some useful code for file operations.
public boolean changeRemoteDirectory(String relativeLocation)
throws SftpException {
curChannel.cd(relativeLocation);
return true;
}
public boolean changeLocalDirectory(String relativeLocation)
curChannel.lcd(relativeLocation);
return true;
}
public boolean rename(String srcFileName, String dstFilename)
throws IOException, SftpException {
curChannel.rename(srcFileName, dstFilename);
return true;
}
In this article, we have seen SFTP File Upload and Download Using Java.
0 Comments
Post a Comment