How To Connect SFTP(Secure File Transfer Protocol ) Server In Spring Boot.

Today Agenda: How To download(read), upload(write) and delete a file from the SFTP server.

In the next ten, minutes you will be performing several operations related to SFTP Server

What Is SFTP?

SFTP provides a secure channel for transferring the files between the hosts.
SFTP protocol is a part of SSH protocol (a remote login application program).
SFTP transfers the file under the connection established by SSH protocol between client and server.
SFTP encrypts the data before sending it.

Let’s Start

Required Tools
Maven
STS
JDK 8
(Attention)Read Each Line carefully

Project Structure

projectStructure
Project Structure Of SFTP

Just Add This Dependency In pom.xml

 <dependency>
        <groupId>com.jcraft</groupId>
        <artifactId>jsch</artifactId>
        <version>0.1.45</version>
    </dependency>

Now Add Your SFTP Server Credential In application.properties file

shftp.host =
shftp.port =  //in general term is 22
shftp.username = bunnytutorials
shftp.password =  bunnytutorials
upload.directory = ./upload

Now get the credential in your SFTP Implementation class

@Value("${shftp.host}")
private String host;
private final int port = 22;
@Value("${shftp.username}")
private String user;
@Value("${shftp.password}")
private String password;
//get the list of files name from the sftp server
//this function will return the list of file's name
	public List<String> getList(String path) {
		List<String> fileNames=new ArrayList<String>();
		try {
			JSch jsch = new JSch();
			Session session = jsch.getSession(user, host, port);
			session.setPassword(password);
			session.setConfig("StrictHostKeyChecking", "no");
			System.out.println("Establishing Connection...");
			session.connect();
			System.out.println("Connection established.");
			System.out.println("Creating SFTP Channel.");
			ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
			sftpChannel.connect();
			System.out.println("SFTP Channel created.");
			sftpChannel.cd(path);
			Vector filelist = sftpChannel.ls(path);
			for (int i = 0; i < filelist.size(); i++) {
				LsEntry entry = (LsEntry) filelist.get(i);
//just uncomment this line then your file name also start printing on the console
//System.out.println(entry.getFilename());
				fileNames.add(entry.getFilename());
			}
			session.disconnect();
			sftpChannel.disconnect();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return fileNames;
	}
//read a file from SFTP and save in your application.properties upload.directory respective path
//this function will create a file according to provided filename and save into provided path in uploadDirectory;
//upload.directory is that variable which is declare in application.properties and get their values in SFTP Implementation class
/**
	 * this function is used for downloading the file from the sftp server hints:
	 * directory : /bunny/
         *fileName : something.extinction
	 */
	@Override
	public void downloadFromSFTP(String SFTPWORKINGDIR, String remoteFile) {
		try {
			JSch jsch = new JSch();
			Session session = jsch.getSession(user, host, port);
			session.setPassword(password);
			session.setConfig("StrictHostKeyChecking", "no");
			System.out.println("Establishing Connection...");
			session.connect();
			System.out.println("Connection established.");
			System.out.println("Creating SFTP Channel.");
			ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
			sftpChannel.connect();
			System.out.println("SFTP Channel created.");
			sftpChannel.cd(SFTPWORKINGDIR);
			FileWriter writer = new FileWriter(uploadDirectory + "/file/" + remoteFile);
			InputStream out = null;
			out = sftpChannel.get(remoteFile);
			BufferedReader br = new BufferedReader(new InputStreamReader(out));
			String strLine = "";
			while ((strLine = br.readLine()) != null) {
				writer.write(strLine);
				writer.write(String.format("%n"));
			}
			session.disconnect();
			sftpChannel.disconnect();
			out.close();
			writer.close();
			br.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	// this function is used for deleting the file from the SFTP server
	// directory hint : /bunny/
	@Override
	public void deleteFile(String SFTPWORKINGDIR, String fileName) {
		try {
			JSch jsch = new JSch();
			Session session = jsch.getSession(user, host, port);
			session.setPassword(password);
			session.setConfig("StrictHostKeyChecking", "no");
			System.out.println("Establishing Connection...");
			session.connect();
			System.out.println("Connection established.");
			System.out.println("Creating SFTP Channel.");
			ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
			sftpChannel.connect();
			System.out.println("SFTP Channel created.");
			sftpChannel.cd(SFTPWORKINGDIR);
			sftpChannel.rm(fileName);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
void uploadOnSFTP(){
                String SFTPWORKINGDIR1 = "/bunnyTutorial/"; //specify your directory name
		FileInputStream fileInputStream = null;
		JSch jsch1 = new JSch();
		Session session1 = jsch1.getSession(user, host, port);
		session1.setPassword(password);
		session1.setConfig("StrictHostKeyChecking", "no");
		System.out.println("Establishing Connection...");
		session1.connect();
		System.out.println("Connection established.");
		System.out.println("Creating SFTP Channel.");
		ChannelSftp sftpChannel1 = (ChannelSftp) session1.openChannel("sftp");
		sftpChannel1.connect();
		System.out.println("SFTP Channel created.");
		sftpChannel1.cd(SFTPWORKINGDIR1);
		File folder = new File(uploadDirectory + "/selected/");
		File[] listOfFiles = folder.listFiles();
		for (File file1 : listOfFiles) {
			if (file1.isFile()) {
				fileInputStream = new FileInputStream(uploadDirectory + "/selected/" + file1.getName());
				sftpChannel1.put(fileInputStream, file1.getName());
				fileInputStream.close();
				file1.delete();
			}
		}
		session1.disconnect();
		sftpChannel1.disconnect();
	}
		

Swagger Configuration
If you don’t have any idea related to swagger then don’t worry a swagger is just a tool by which we can test out rest API’s
If you want to learn more about the swagger then click on this link:

If you want to remove the swagger then simply remove the SwaggerConfig.java class from the com.example.config folder.

Swagger
Duplextree team configures the swagger for testing the rest API if you want to remove the swagger then simply remove the SwaggerConfig.java class from the com.example.config folder.
And If Don’t have any idea related to swagger then click on this link:


Raman

Related post

Leave a Reply

Your email address will not be published. Required fields are marked *