SFTP SSH Jcraft[JSch] - Yash-777/SteamingServlet GitHub Wiki
Java Secure Channel
JSch -JSch is a pure Java implementation of SSH2.
JSch allows you to connect to an sshd
server and use port forwarding, X11 forwarding, file transfer, etc., and you can integrate its functionality into your own Java programs.
JSch - Examples - Sftp.java
https://stackoverflow.com/questions/15108923/sftp-file-transfer-using-java-jsch?lq=1
https://stackoverflow.com/questions/4826821/copying-a-file-in-sftp-with-jsch-library
import java.io.*;
import java.util.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.jcraft.jsch.*;
//https://mvnrepository.com/artifact/com.jcraft/jsch/0.1.54
public class SFTP_RemoteFileTransfer {
private static final Log log = LogFactory.getLog(SFTP_RemoteFileTransfer.class);
// https://www.ghacks.net/2019/07/29/how-to-setup-an-sftp-server-in-windows-using-openssh/
static String sftpHost, sftpUsername, sftpPassword;
static int sftpPort;
static {
sftpHost = "sftp.yash-ssi.net";
sftpPort = 22;
sftpUsername = "*****";
sftpPassword = "*****";
}
static String destinationDir = "/GitHub/Yash-777/Project/Files",
archivalDir = "/GitHub/Yash-777/Project/FilesArchival";
public static void main(String[] args) throws Exception {
String NewFilePath = "C:/Yash/Baeldung.p12";
File newFile = new File(NewFilePath);
InputStream fileContent = new FileInputStream(newFile);
String SFTP_PathFileName = newFile.getName();
String archivalDir = null;
copyReportToDestination(fileContent, SFTP_PathFileName, destinationDir, archivalDir);
}
public static void copyReportToDestination(InputStream fileContent, String fileName, String destinationDir, String archivalDir) throws Exception{
Session session = null;
Channel channel = null;
ChannelSftp channelSftp = null;
try {
JSch jsch = new JSch();
session = jsch.getSession(sftpUsername, sftpHost, sftpPort);
session.setPassword(sftpPassword);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
channel = session.openChannel("sftp");
channel.connect();
channelSftp = (ChannelSftp) channel;
channelSftp.cd(destinationDir);
// Move old reports to archive location
if(archivalDir != null)
moveExistingFilesToArchive(channelSftp, destinationDir, archivalDir);
// copy new report to destination directory
copyReportsToDestination(channelSftp, fileContent, fileName, destinationDir);
channel.disconnect();
session.disconnect();
if (session.isConnected()) {
session.disconnect();
}
} catch (JSchException|SftpException e) {
throw new Exception("Failed while transfering file and caught Exception!:"+ e);
}
}
static SimpleDateFormat dateFormat = new java.text.SimpleDateFormat("yyyyMMdd_HH_mm_ss");
public static void moveExistingFilesToArchive(ChannelSftp channelSftp, String sftpWorkingDir, String destinationDir) throws Exception {
try {
@SuppressWarnings("unchecked")
Vector<ChannelSftp.LsEntry> filesList = channelSftp.ls("*.*");
log.info("filesList size:" + filesList.size());
if (!filesList.isEmpty()) {
for (ChannelSftp.LsEntry entry : filesList) {
String filename = entry.getFilename();
log.info("Filename::" + filename);
String localFile = sftpWorkingDir + "/" + filename;
String archivalFilename = filename;
String[] parts = null;
if (filename.contains(".")) { // filename.matches("\\*.\\*")
log.info("File name change");
parts = filename.split("\\.");
// ArchivalTimestamp to be appended to filename
String timeStamp = dateFormat.format(new Date());
archivalFilename = parts[0] + "_" + timeStamp + "." + parts[1];
}
String remoteDir = destinationDir + "/" + archivalFilename;
log.info("Ready for transfer" + remoteDir + "\n" + localFile);
channelSftp.cd(destinationDir);
channelSftp.rename(localFile, remoteDir);
channelSftp.cd(sftpWorkingDir);
}
}
} catch (SftpException e) {
throw new Exception("Failed while transfering file and caught SftpException!:"+ e);
}
}
public static void copyReportsToDestination(ChannelSftp channelSftp, InputStream fileContent, String fileName, String destinationDir) throws Exception {
try {
channelSftp.cd(destinationDir);
log.info("Report upload to Remote directory Starts");
channelSftp.put(fileContent, destinationDir+"/"+fileName);
fileContent.close();
log.info("File uploaded successfully - "+ destinationDir);
} catch(SftpException|IOException e) {
throw new Exception("Failed while transfering file and caught Exception!:"+ e);
}
}
}