OverviewIn this post we will show you how to transfer files from a local host to a remote server and download files from a remote server to local host via SFTP in Spring Boot applications. In order to transfer files via SFTP in Java applications we also explore the JSch library. Table of contents
Creating Spring Boot Project with Spring Tool Suite on EclipseFrom Spring Tool Suite IDE select menu File -> New -> Spring Starter Project. On the New Spring Starter Project popup input new project spring-boot-sftp information as following screenshot. Add JSch Java library to Gradle or Maven projectIn order to transfer files via SFTP we will use JSch (or Java Secure Channel) library which is a pure Java implementation of SSH2. For more information about the library you can visit JSch home page at www.jcraft.com/jsch Add the following dependency to your build.gradle file.
Or use the following XML to add dependency if you are using Maven build for your project.
Create File Transfer Service interfaceCreate new package named dev.simplesolution.sftp.service, and add new interface named FileTransferService to this package with source code as following
Implement File Transfer Service classCreate a new package named dev.simplesolution.sftp.service.impl, and add a class named FileTransferServiceImpl to this new package.
Add SFTP configurations to application.propertiesAdd following configurations to properties file at \spring-boot-sftp\src\main\resources\application.properties
Test your codeCreate TestSftpFileTransfer as the following code to use your file transfer service implementation above.
Final applicationAfter steps above your project will be as the screenshot below. Run project to see result in log console. Download Source CodeThe source code in this article can be found at: github.com/simplesolutiondev/spring-boot-sftp or clone at:
or download at: Download Source Code Happy Coding 😊 |