File transfer is a common requirement in modern software development, especially when uploading files to remote servers. SFTP (SSH File Transfer Protocol) is a secure file transfer protocol that is widely used to transfer files between clients and servers. This article will introduce in detail how to use Java to implement SFTP file upload and provide complete code examples.
1. What is SFTP
SFTP (SSH File Transfer Protocol) is a file transfer protocol based on the SSH protocol. Unlike FTP, SFTP transmits files through encrypted SSH connections, ensuring the security of data transmission. SFTP is usually used in scenarios where files need to be transferred securely, such as uploading log files, backing up data, etc.
2. Implement SFTP using JSch library
In Java, we can use the JSch library to implement SFTP file upload. JSch is a pure Java implementation SSH2 library that supports SFTP, SCP, port forwarding and other functions. This article will use JSch to implement SFTP file upload.
3. Implementation steps
3.1 Add dependencies
First, we need to add dependencies of the JSch library in our project. If you are using a Maven project, you can add the following dependencies:
<dependency> <groupId></groupId> <artifactId>jsch</artifactId> <version>0.1.55</version> </dependency>
3.2 Create SFTP tool class
Next, we create a SftpUploadUtil tool class to encapsulate SFTP connection, file upload, download and delete operations. Here is the complete code implementation:
package ; import .*; import ; import ; import ; import org.; import org.; public class SftpUploadUtil { private static final Logger logger = (); private Session session; private ChannelSftp channel; /** * Connect to the SFTP server * @param host SFTP server host name * @param port SFTP server port * @param username Username * @param password * @throws JSchException if connection fails */ public void connect(String host, int port, String username, String password) throws JSchException { JSch jsch = new JSch(); session = (username, host, port); (password); Properties config = new Properties(); ("StrictHostKeyChecking", "no"); (config); (); channel = (ChannelSftp) ("sftp"); (); } /** * Upload files to SFTP server * @param localFilePath local file path * @param remoteFilePath remote file path * @throws Exception If upload fails */ public void uploadFile(String localFilePath, String remoteFilePath) throws Exception { File localFile = new File(localFilePath); String remoteDir = (0, ('/')); try { (remoteDir); } catch (SftpException e) { ("Creating remote directory: {}", remoteDir); createRemoteDirectory(remoteDir); } try (FileInputStream fis = new FileInputStream(localFile)) { (fis, remoteFilePath); } } /** * Download the file from the SFTP server * @param remoteFilePath remote file path * @param localFilePath local file path * @throws Exception If the download fails */ public void downloadFile(String remoteFilePath, String localFilePath) throws Exception { (remoteFilePath, localFilePath); } /** * Delete files on the SFTP server * @param remoteFilePath remote file path * @throws SftpException If deletion fails */ public void deleteFile(String remoteFilePath) throws SftpException { (remoteFilePath); } /** * Create a remote directory on the SFTP server * @param path Remote directory path * @throws SftpException If creation fails */ private void createRemoteDirectory(String path) throws SftpException { String[] folders = ("/"); StringBuilder currentPath = new StringBuilder(); for (String folder : folders) { if (!()) { ("/").append(folder); try { (()); } catch (SftpException e) { (()); ("Created directory: {}", ()); } } } } /** * Disconnect from the SFTP server */ public void disconnect() { if (channel != null) { (); } if (session != null) { (); } } }
3.3 Code parsing
Connect method: used to connect to an SFTP server. Create an SSH session through the JSch library and open an SFTP channel.
uploadFile method: used to upload local files to the SFTP server. If the remote directory does not exist, the directory is automatically created.
downloadFile method: used to download files from SFTP server to local.
deleteFile method: used to delete files on the SFTP server.
createRemoteDirectory method: used to create a remote directory on an SFTP server.
disconnect method: used to disconnect from the SFTP server.
3.4 Use examples
Here is a simple usage example showing how to upload files to an SFTP server:
public class SftpExample { public static void main(String[] args) { SftpUploadUtil sftpUtil = new SftpUploadUtil(); try { // Connect to SFTP server ("", 22, "username", "password"); // Upload file ("/path/to/local/", "/path/to/remote/"); // Download the file ("/path/to/remote/", "/path/to/local/downloaded_file.txt"); // Delete the file ("/path/to/remote/"); } catch (Exception e) { (); } finally { // Disconnect (); } } }
4. Summary
This article details how to use Java and JSch libraries to implement SFTP file upload. By encapsulating the SftpUploadUtil tool class, we can easily implement files transmission, download and delete operations.
The above is the detailed tutorial and code analysis of Java's SFTP file upload. For more information about Java SFTP file upload, please pay attention to my other related articles!