maven依赖
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>
代码
import com.jcraft.jsch.*;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
public class JSchSFTPFileTransfer {
public static void main(String[] args) {
String host = "";
String user = "";
String password = "";
int port = ;
String remoteFilePath = "";
String localFilePath = "";
JSch jsch = new JSch();
Session session = null;
ChannelSftp sftpChannel = null;
InputStream inputStream = null;
OutputStream outputStream = null;
try {
session = jsch.getSession(user, host, port);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword(password);
session.connect();
sftpChannel = (ChannelSftp) session.openChannel("sftp");
sftpChannel.connect();
int lastSlashIndex = remoteFilePath.lastIndexOf("/");
String path = remoteFilePath.substring(0, lastSlashIndex);
File file = new File(path);
if (!file.exists()) {
try {
file.mkdirs();
} catch (Exception e) {
System.out.println("=====jSchSFTPFileTransfer创建文件夹失败!====");
}
}
inputStream = sftpChannel.get(remoteFilePath);
outputStream = new java.io.FileOutputStream(localFilePath);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
System.out.println("=====jSchSFTPFileTransfer文件下载成功!===="+localFilePath);
} catch (JSchException | SftpException | java.io.IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (java.io.IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (java.io.IOException e) {
e.printStackTrace();
}
}
if (sftpChannel != null && sftpChannel.isConnected()) {
sftpChannel.disconnect();
}
if (session != null && session.isConnected()) {
session.disconnect();
}
}
}
}