java实现sftp文件上传下载
<!-- sftp -->
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.54</version>
</dependency>
public static void uploadFile(String filePath, String ftpPath, String username, String password, String host, Integer port) {
FileInputStream input = null;
ChannelSftp sftp = null;
try {
JSch jsch = new JSch();
com.jcraft.jsch.Session sshSession = jsch.getSession(username, host, port);
sshSession.setPassword(password);
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
sshSession.connect();
sftp = (ChannelSftp) sshSession.openChannel("sftp");
sftp.connect();
try {
Vector ls = sftp.ls(ftpPath);
} catch (SftpException e) {
sftp.mkdir(ftpPath);
}
sftp.cd(ftpPath);
String filename = filePath.substring(filePath.lastIndexOf(File.separator) + 1);
input = new FileInputStream(new File(filePath));
sftp.put(input, filename);
input.close();
sftp.disconnect();
sshSession.disconnect();
System.out.println("================上传成功!==================");
} catch (Exception e) {
System.out.println("================上传失败!==================");
e.printStackTrace();
}
}
public static void downloadFile(String directory, String downloadFile, String saveFile, String username, String password, String host, Integer port) {
ChannelSftp sftp = null;
try {
JSch jsch = new JSch();
com.jcraft.jsch.Session sshSession = jsch.getSession(username, host, port);
sshSession.setPassword(password);
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
sshSession.connect();
sftp = (ChannelSftp) sshSession.openChannel("sftp");
sftp.connect();
if (directory != null && !"".equals(directory)) {
sftp.cd(directory);
}
FileOutputStream output = new FileOutputStream(new File(saveFile));
sftp.get(downloadFile, output);
output.close();
sftp.disconnect();
sshSession.disconnect();
System.out.println("================下载成功!==================");
} catch (SftpException | FileNotFoundException | JSchException e) {
log.error("文件下载异常!", e);
} catch (IOException e) {
e.printStackTrace();
}
}