SFTP實(shí)現(xiàn)文件上傳/下載功能
maven依賴:
????com.jcraft 0.1.55
????commons-io 2.6
文件傳輸協(xié)議: FTP、SFTP和SCP
package com.example.demo.ftp;
import com.jcraft.jsch.*;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.Properties;
import java.util.Vector;
/**
* @Author: Andy.han
* @Description: SFTPUtils {
* <dependency>
* <groupId>com.jcraft</groupId>
* <artifactId>jsch</artifactId>
* <version>0.1.55</version>
* </dependency>
* <dependency>
* <groupId>commons-io</groupId>
* <artifactId>commons-io</artifactId>
* <version>2.6</version>
* </dependency>
* }
* @Date: Created in 13:45 2019/5/30.
* @Modified By:
*/
public class SFTPUtils {
private transient Logger log = LoggerFactory.getLogger(this.getClass());
private String logId;
private ChannelSftp sftp;
private Session session;
/**
* FTP 登錄用戶名
*/
private String username;
/**
* FTP 登錄密碼
*/
private String password;
/**
* 私鑰
*/
private String privateKey;
/**
* FTP 服務(wù)器地址IP地址
*/
private String host;
/**
* FTP 端口
*/
private int port;
/**
* @param username
* @param password
* @param host
* @param port
* @param logId
* @Author: Andy.han
* @Description: 構(gòu)造基于密碼認(rèn)證的sftp對(duì)象
* @Return: SFTPUtils
* @Date: 2019/5/30 13:54
*/
public SFTPUtils(String username, String password, String host, int port, String logId) {
this.username = username;
this.password = password;
this.host = host;
this.port = port;
this.logId = logId;
}
/**
* @param username
* @param host
* @param port
* @param privateKey
* @param logId
* @Author: Andy.han
* @Description: 構(gòu)造基于秘鑰認(rèn)證的sftp對(duì)象
* @Return: SFTPUtils
* @Date: 2019/5/30 13:55
*/
public SFTPUtils(String username, String host, int port, String privateKey, String logId) {
this.username = username;
this.host = host;
this.port = port;
this.privateKey = privateKey;
this.logId = logId;
}
public SFTPUtils() {
}
/**
* @param
* @Author: Andy.han
* @Description: 連接sftp服務(wù)器
* @Return: void
* @Date: 2019/5/30 13:56
*/
public void login() {
try {
JSch jsch = new JSch();
if (privateKey != null) {
jsch.addIdentity(privateKey);// 設(shè)置私鑰
log.info("sftp connect,path of private key file:{}, logId:{}", privateKey, logId);
}
log.info("sftp connect by host:{} username:{}, logId:{}", host, username, logId);
session = jsch.getSession(username, host, port);
log.info("Session is build, logId:{}", logId);
if (password != null) {
session.setPassword(password);
}
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
log.info("Session is connected, logId:{}", logId);
Channel channel = session.openChannel("sftp");
channel.connect();
log.info("channel is connected, logId:{}", logId);
sftp = (ChannelSftp) channel;
log.info(String.format("sftp server host:[%s] port:[%s] is connect successfull, logId:{}", host, port, logId));
} catch (JSchException e) {
log.error("Cannot connect to specified sftp server : {}:{} \n Exception message is: {} logId: {}", new Object[]{host, port, e.getMessage(), logId});
}
}
/**
* @param
* @Author: Andy.han
* @Description: 關(guān)閉連接 server
* @Return: void
* @Date: 2019/5/30 13:58
*/
public void logout() {
if (sftp != null) {
if (sftp.isConnected()) {
sftp.disconnect();
log.info("sftp is closed already, logId:{}", logId);
}
}
if (session != null) {
if (session.isConnected()) {
session.disconnect();
log.info("sshSession is closed already, logId:{}", logId);
}
}
}
/**
* @param directory 上傳到該目錄
* @param sftpFileName sftp端文件名
* @param input 輸入流
* @Author: Andy.han
* @Description: 將輸入流的數(shù)據(jù)上傳到sftp作為文件
* @Return: void
* @Date: 2019/5/30 13:58
*/
public void upload(String directory, String sftpFileName, InputStream input) throws SftpException {
try {
sftp.cd(directory);
} catch (SftpException e) {
log.warn("directory is not exist, logId:{}", logId);
sftp.mkdir(directory);
sftp.cd(directory);
}
sftp.put(input, sftpFileName);
log.info("file:{} is upload successful, logId:{}", sftpFileName, logId);
}
/**
* @param directory 上傳到sftp目錄
* @param uploadFile 要上傳的文件,包括路徑
* @throws FileNotFoundException
* @throws SftpException
* @Author: Andy.han
* @Description: 上傳單個(gè)文件
* @Return: void
* @Date: 2019/5/30 13:59
*/
public void upload(String directory, String uploadFile, String fileName) throws FileNotFoundException, SftpException {
File file = new File(uploadFile);
upload(directory, fileName, new FileInputStream(file));
}
/**
* @param directory 上傳到sftp目錄
* @param sftpFileName 文件在sftp端的命名
* @param byteArr 要上傳的字節(jié)數(shù)組
* @throws SftpException
* @Author: Andy.han
* @Description: 將byte[]上傳到sftp,作為文件。注意:從String生成byte[]是,要指定字符集。
* @Return: void
* @Date: 2019/5/30 14:02
*/
public void upload(String directory, String sftpFileName, byte[] byteArr) throws SftpException {
upload(directory, sftpFileName, new ByteArrayInputStream(byteArr));
}
/**
* @param directory 上傳到sftp目錄
* @param sftpFileName 文件在sftp端的命名
* @param dataStr 待上傳的數(shù)據(jù)
* @param charsetName sftp上的文件,按該字符編碼保存
* @throws UnsupportedEncodingException
* @throws SftpException
* @Author: Andy.han
* @Description: 將字符串按照指定的字符編碼上傳到sftp
* @Return: void
* @Date: 2019/5/30 14:03
*/
public void upload(String directory, String sftpFileName, String dataStr, String charsetName) throws UnsupportedEncodingException, SftpException {
upload(directory, sftpFileName, new ByteArrayInputStream(dataStr.getBytes(charsetName)));
}
/**
* @param directory 下載目錄
* @param downloadFile 下載的文件
* @param saveFile 存在本地的路徑
* @throws SftpException
* @throws FileNotFoundException
* @Author: Andy.han
* @Description: 下載文件
* @Return: void
* @Date: 2019/5/30 14:05
*/
public void download(String directory, String downloadFile, String saveFile) throws SftpException, FileNotFoundException {
if (directory != null && !"".equals(directory)) {
sftp.cd(directory);
}
File file = new File(saveFile);
sftp.get(downloadFile, new FileOutputStream(file));
log.info("file:{} is download successful, logId:{}", downloadFile, logId);
}
/**
* @param directory 下載目錄
* @param downloadFile 下載的文件名
* @throws SftpException
* @throws IOException
* @Author: Andy.han
* @Description: 下載文件
* @Return: byte[]
* @Date: 2019/5/30 14:06
*/
public byte[] download(String directory, String downloadFile) throws SftpException, IOException {
if (directory != null && !"".equals(directory)) {
sftp.cd(directory);
}
InputStream is = sftp.get(downloadFile);
byte[] fileData = IOUtils.toByteArray(is);
log.info("file:{} is download successful, logId:{}", downloadFile, logId);
return fileData;
}
/**
* @param directory 要?jiǎng)h除文件所在目錄
* @param deleteFile 要?jiǎng)h除的文件
* @throws SftpException
* @Author: Andy.han
* @Description: 刪除文件
* @Return: void
* @Date: 2019/5/30 14:07
*/
public void delete(String directory, String deleteFile) throws SftpException {
sftp.cd(directory);
sftp.rm(deleteFile);
}
/**
* @param directory
* @throws SftpException
* @Author: Andy.han
* @Description: 列出目錄下的文件
* @Return: Vector<?>
* @Date: 2019/5/30 14:08
*/
public Vector<?> listFiles(String directory) throws SftpException {
return sftp.ls(directory);
}
public static void main(String[] args) throws Exception {
SFTPUtils sftp = new SFTPUtils("****", "****", "****", 22, null);
sftp.login();
File file = new File("D:\\test.txt");
InputStream is = new FileInputStream(file);
sftp.upload("/home/SFTP/**/**/**/", "zj.txt", is);
sftp.logout();
}
}