java实现scp功能实现目录下所有文件拷贝至指定服务器

1、添加pom依赖

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

2、示例代码

public static void main(String[] args) throws IOException {
try {
// 初始化JSch对象
JSch jsch = new JSch();
// 创建一个会话,设置用户名、主机IP和端口(默认22)
Session session = jsch.getSession("用户名", "ip", 22);
// 设置密码(也可以使用key-based authentication)
session.setPassword("密码");
// 设置第一次登陆时提示,可选值:(ask | yes | no)
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
// 建立连接
session.connect();
// 创建一个SFTP通道
Channel channel = session.openChannel("sftp");
channel.connect();
// 获取SFTP客户端
ChannelSftp sftpClient = (ChannelSftp) channel;
// 准备本地文件夹路径与远程目标路径
String localFolderPath = "E:/目录/";
String remoteDirPath = "/data/transfer/";
File localFolder = new File(localFolderPath);
if (localFolder.isDirectory()) {
uploadFolder(sftpClient, localFolderPath, remoteDirPath);
} else {
System.out.println(localFolderPath + " is not a directory.");
}
// 关闭资源
sftpClient.quit();
session.disconnect();

} catch (JSchException | SftpException | FileNotFoundException e) {
e.printStackTrace();
}
}

private static void uploadFolder(ChannelSftp sftpClient, String localFolderPath, String remoteDirPath) throws SftpException, IOException {
File localFolder = new File(localFolderPath);
File[] files = localFolder.listFiles();
if (files != null) {
for (File file : files) {
if (file.isDirectory()) {
// 如果是目录,则在远程服务器上创建对应目录并递归上传
String newRemoteDirPath = remoteDirPath + file.getName() + "/";
sftpClient.mkdir(newRemoteDirPath);
uploadFolder(sftpClient, file.getAbsolutePath(), newRemoteDirPath);
} else {
// 如果是文件,则上传到远程服务器
String localFilePath = file.getAbsolutePath();
String remoteFilePath = remoteDirPath + file.getName();
FileInputStream fis = new FileInputStream(file);
sftpClient.put(fis, remoteFilePath);
fis.close();
}
}
}
}
posted @ 2024-02-26 08:36  懂得归零  阅读(75)  评论(0编辑  收藏  举报