sftp 下载一个目录下所有文件并删除原目录下文件 java 实现
时间: 2024-02-06 16:04:35 浏览: 25
你可以使用 JSch 这个 Java 的 SFTP 客户端库来实现这个功能。
以下是一个示例代码,可以连接到远程 SFTP 服务器,下载指定目录下的所有文件,并删除原目录下的文件:
```java
import com.jcraft.jsch.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Properties;
import java.util.Vector;
public class SftpClient {
public static void main(String[] args) {
String host = "your_host";
String username = "your_username";
String password = "your_password";
String remoteDirectory = "/path/to/remote/directory";
String localDirectory = "/path/to/local/directory";
JSch jsch = new JSch();
Session session = null;
ChannelSftp channelSftp = null;
try {
session = jsch.getSession(username, host, 22);
session.setPassword(password);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
channelSftp = (ChannelSftp) session.openChannel("sftp");
channelSftp.connect();
// 获取远程目录下所有文件
Vector<ChannelSftp.LsEntry> files = channelSftp.ls(remoteDirectory);
// 下载所有文件并删除原目录下文件
for (ChannelSftp.LsEntry file : files) {
String fileName = file.getFilename();
// 跳过当前目录和上级目录
if (fileName.equals(".") || fileName.equals("..")) {
continue;
}
// 下载文件
InputStream inputStream = channelSftp.get(remoteDirectory + "/" + fileName);
File localFile = new File(localDirectory + "/" + fileName);
FileOutputStream outputStream = new FileOutputStream(localFile);
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
}
inputStream.close();
outputStream.close();
// 删除原文件
channelSftp.rm(remoteDirectory + "/" + fileName);
}
System.out.println("文件下载完成");
} catch (JSchException | SftpException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (channelSftp != null) {
channelSftp.disconnect();
}
if (session != null) {
session.disconnect();
}
}
}
}
```
你需要将示例代码中的 `your_host`、`your_username`、`your_password`、`/path/to/remote/directory`、`/path/to/local/directory` 替换为你实际的 SFTP 服务器地址、用户名、密码、远程目录和本地目录。
注意:该示例代码并未进行异常处理和错误处理,你需要根据实际情况进行修改和完善。