要将URL地址文件流上传到SFTP服务器的特定目录下,你可以通过JSch库和ChannelSftp对象的put()
方法来实现。以下是一个示例代码演示如何实现:
package com.credithc.loan.common.platform.bohai.util; import com.jcraft.jsch.*; import java.io.IOException; import java.io.InputStream; import java.net.URL; public class SftpUploader { public static void main(String[] args) { String sftpHost = "your_sftp_host"; int sftpPort = 22; String sftpUser = "your_sftp_username"; String sftpPassword = "your_sftp_password"; // URL地址文件 String url = "https://example.com/file.txt"; try { // 创建JSch对象 JSch jsch = new JSch(); // 建立SFTP会话 Session session = jsch.getSession(sftpUser, sftpHost, sftpPort); session.setPassword(sftpPassword); session.setConfig("StrictHostKeyChecking", "no"); session.connect(); // 打开SFTP通道 ChannelSftp channelSftp = (ChannelSftp) session.openChannel("sftp"); channelSftp.connect(); // 获取URL地址文件输入流 URL fileUrl = new URL(url); InputStream inputStream = fileUrl.openStream(); // 从URL地址创建文件名 String fileName = getFileNameFromUrl(url); fileName = "test01_applydetail_20230829_006.pdf"; // 指定远程目录路径 String remoteDirectory = "/opt/test/"; // 拼接完整的远程文件路径 String remoteFilePath = remoteDirectory + fileName; System.out.println("完整的远程文件路径:"+remoteDirectory); // 切换到远程目录 channelSftp.cd(remoteDirectory); // 将文件流上传到SFTP服务器指定目录下 channelSftp.put(inputStream, remoteFilePath); // 关闭资源 inputStream.close(); channelSftp.disconnect(); session.disconnect(); System.out.println("File uploaded successfully to SFTP server."); } catch (JSchException | SftpException | IOException e) { e.printStackTrace(); } } // 从URL地址获取文件名 private static String getFileNameFromUrl(String url) { String[] segments = url.split("/"); return segments[segments.length - 1]; } }
在上述示例代码中,添加了以下内容来实现将文件流上传到特定目录:
- 定义
remoteDirectory
变量并设置为目标SFTP服务器上的远程目录路径。 - 使用
channelSftp.cd(remoteDirectory)
切换到远程目录。 - 将
remoteFilePath
设置为远程目录和文件名的组合。 - 使用
channelSftp.put(inputStream, remoteFilePath)
将文件流上传到SFTP服务器的特定目录下。
确保在使用代码之前,你已经将JSch库添加到项目的依赖中,并根据需要修改相应的SFTP连接参数和远程目录路径。