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();
}
}
}
}

浙公網安備 33010602011771號