原创博主:郑浩-https://me.csdn.net/u013045437 文章不错,推荐收藏关注!!! 转载:https://blog.csdn.net/u013045437/article/details/91619486
 
最进想学习下java如何操作sftp服务器,找了几篇文章,感觉不错就分享了下,亲测SFTPUtil工具类可以。
 
1.maven依赖包
 
      <dependency>
      <groupId>com
.jcraft
</groupId
>
      <artifactId>jsch
</artifactId
>
      <version>0.1.54</version
>
    </dependency
>
    <!-- https
://mvnrepository
.com
/artifact
/com
.trilead
/trilead
-ssh2 
-->
    <dependency>
      <groupId>com
.trilead
</groupId
>
      <artifactId>trilead
-ssh2
</artifactId
>
      <version>1.0.0-build221
</version
>
    </dependency
>
    <!-- https
://mvnrepository
.com
/artifact
/commons
-fileupload
/commons
-fileupload 
-->
    <dependency>
      <groupId>commons
-fileupload
</groupId
>
      <artifactId>commons
-fileupload
</artifactId
>
      <version>1.3</version
>
    </dependency
>
   <dependency>
      <groupId>commons
-io
</groupId
>
      <artifactId>commons
-io
</artifactId
>
      <version>2.4</version
>
    </dependency
>
 
2.SFTPUtil工具类
 
package com
.zfc
.util
;
import com
.jcraft
.jsch
.*
;
import org
.apache
.commons
.io
.IOUtils
;
import java
.io
.*
;
import java
.util
.ArrayList
;
import java
.util
.List
;
import java
.util
.Properties
;
import java
.util
.Vector
;
public class SFTPUtil {
    private ChannelSftp sftp
;
    private Session session
;
    
    private String username
;
    
    private String password
;
    
    private String privateKey
;
    
    private String host
;
    
    private int port
;
    
    public SFTPUtil(String username
, String password
, String host
, int port
){
        this.username 
= username
;
        this.password 
= password
;
        this.host 
= host
;
        this.port 
= port
;
    }
    
    public SFTPUtil(String username
, String host
, int port
, String privateKey
) {
        this.username 
= username
;
        this.host 
= host
;
        this.port 
= port
;
        this.privateKey 
= privateKey
;
    }
    public SFTPUtil() {
    }
    public static void main(String
[] args
) throws SftpException
, IOException 
{
        String host 
= "127.0.0.1";
        int port 
= 22;
        String username 
= "root";
        String password 
= "123456";
        String dir 
= "/xxx";
        String filename 
= "test.text";
        SFTPUtil sftp 
= new SFTPUtil(username
, password
, host
, port
);
        sftp
.login();
        sftp
.download(dir
,filename
,"a.txt");
        sftp
.logout();
    }
    public void login(){
        try {
            JSch  jSch 
= new JSch();
            if (privateKey 
!= null
){
                jSch
.addIdentity(privateKey
);
            }
            session 
= jSch
.getSession(username
,host
,port
);
            if (password 
!= null
){
                session
.setPassword(password
);
            }
            Properties config 
= new Properties();
            config
.put("StrictHostKeyChecking","no");
            session
.setConfig(config
);
            session
.connect();
            System
.out
.println("Session connected!");
            Channel channel 
= session
.openChannel("sftp");
            channel
.connect();
            System
.out
.println("Channel connected!");
            sftp 
= (ChannelSftp
) channel
;
        } catch (JSchException e
){
            e
.printStackTrace();
        }
    }
    
    public void logout() {
        if (sftp 
!= null
) {
            if (sftp
.isConnected()) {
                sftp
.disconnect();
            }
        }
        if (session 
!= null
) {
            if (session
.isConnected()) {
                session
.disconnect();
            }
        }
    }
    
    public boolean upload(String directory
, String sftpFileName
, InputStream input
) throws SftpException 
{
        try {
            if (directory 
!= null 
&& !"".equals(directory
)) {
                sftp
.cd(directory
);
            }
            sftp
.put(input
, sftpFileName
);  
            return true;
        } catch (SftpException e
) {
            return false;
        }
    }
    public void cd(String directory
) throws SftpException 
{
        if (directory 
!= null 
&& !"".equals(directory
) && !"/".equals(directory
)) {
            sftp
.cd(directory
);
        }
    }
    
    public void download(String directory
, String downloadFile
, String saveFile
) {
        System
.out
.println("download:" + directory 
+ " downloadFile:" + downloadFile 
+ " saveFile:" + saveFile
);
        File file 
= null
;
        try {
            if (directory 
!= null 
&& !"".equals(directory
)) {
                sftp
.cd(directory
);
            }
            file 
= new File(saveFile
);
            if (!file
.exists()){
                file
.createNewFile();
            }
            sftp
.get(downloadFile
, new FileOutputStream(file
));
        } catch (SftpException e
) {
            e
.printStackTrace();
            if (file 
!= null
) {
                file
.delete();
            }
        } catch (FileNotFoundException e
) {
            e
.printStackTrace();
            if (file 
!= null
) {
                file
.delete();
            }
        }catch (Exception e
){
            e
.printStackTrace();
        }finally {
            if (file 
!= null
) {
                file
.delete();
            }
        }
    }
    
    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
);
        return fileData
;
    }
    
    public void delete(String directory
, String deleteFile
) throws SftpException 
{
        if (directory 
!= null 
&& !"".equals(directory
)) {
            sftp
.cd(directory
);
        }
        sftp
.rm(deleteFile
);
    }
    
    public Vector
<?> listFiles(String directory
) throws SftpException 
{
        return sftp
.ls(directory
);
    }
    public boolean isExistsFile(String directory
, String fileName
) {
        List
<String> findFilelist 
= new ArrayList();
        ChannelSftp
.LsEntrySelector selector 
= new ChannelSftp.LsEntrySelector() {
            @Override
            public int select(ChannelSftp
.LsEntry lsEntry
) {
                if (lsEntry
.getFilename().equals(fileName
)) {
                    findFilelist
.add(fileName
);
                }
                return 0;
            }
        };
        try {
            sftp
.ls(directory
, selector
);
        } catch (SftpException e
) {
            e
.printStackTrace();
        }
        if (findFilelist
.size() > 0) {
            return true;
        } else {
            return false;
        }
    }
    public ChannelSftp 
getSftp() {
        return sftp
;
    }
    public void setSftp(ChannelSftp sftp
) {
        this.sftp 
= sftp
;
    }
    public Session 
getSession() {
        return session
;
    }
    public void setSession(Session session
) {
        this.session 
= session
;
    }
    public String 
getUsername() {
        return username
;
    }
    public void setUsername(String username
) {
        this.username 
= username
;
    }
    public String 
getPassword() {
        return password
;
    }
    public void setPassword(String password
) {
        this.password 
= password
;
    }
    public String 
getPrivateKey() {
        return privateKey
;
    }
    public void setPrivateKey(String privateKey
) {
        this.privateKey 
= privateKey
;
    }
    public String 
getHost() {
        return host
;
    }
    public void setHost(String host
) {
        this.host 
= host
;
    }
    public int getPort() {
        return port
;
    }
    public void setPort(int port
) {
        this.port 
= port
;
    }
}
 
3.下载文件使用
 
package com
.zqf
.cmbc
.service
;
 
import com
.zqf
.cmbc
.tools
.FileUtils
;
import com
.zqf
.cmbc
.tools
.GPGUtil
;
import com
.zqf
.cmbc
.tools
.SFTPUtil
;
import com
.zqf
.common
.exception
.TpErrorCodeGeneral
;
import com
.zqf
.common
.model
.BaseResult
;
import com
.zqf
.common
.utils
.DateUtils
;
import com
.zqf
.common
.utils
.service
.ErrorLogService
;
import org
.springframework
.beans
.factory
.annotation
.Autowired
;
import org
.springframework
.beans
.factory
.annotation
.Value
;
import org
.springframework
.stereotype
.Service
;
 
import javax
.annotation
.Resource
;
import java
.io
.File
;
import java
.io
.FileInputStream
;
import java
.util
.ArrayList
;
import java
.util
.Date
;
import java
.util
.List
;
 
 
@Service
public class XiaoMiFtpService {
 
 
    @Resource
    ErrorLogService errorLogService
;
    @Autowired
    private XiaoMiNotifyService notifyService
;
 
    @Value("${xiaomi_ftp_host}")
    private String xiaomiFtpHost
;
 
    @Value("${xiaomi_ftp_port}")
    private String xiaomiFtpPort
;
 
    @Value("${xiaomi_ftp_user}")
    private String xiaomiFtpUser
;
 
    @Value("${xiaomi_prikey_file}")
    private String xiaomiPriKeyFile
;
 
    @Value("${xiaomi_ftp_local_file_path}")
    private String XIAOMI_LOCAL_FilPath
;
 
 
    private static final String SFTPDirectory 
= "/home";
 
    private static String todayDownLoadFile 
= null
;
    private static String todayCsvFilePath 
= null
;
    private static String todayGpgFilePath 
= null
;
 
    private boolean firstExistsFileFlag 
= false;
 
 
    
    public void sync( int times
) {
        String localFilePath 
= this.initLocalFilePath();
 
        
        String gpgFileName 
= "zhiqing" + DateUtils
.getCurrentMonth() + "." + DateUtils
.getCurrentDay() + "-" + times 
+".xlsx";
 
        
        if (gpgFileName
.equals(todayDownLoadFile
)) {
            System
.out
.println(DateUtils
.getStrDate()+ " 今日文件已经下载:" + todayDownLoadFile
);
            return;
        }
 
        
        if (isLocalFileExists(localFilePath 
+ "/" + gpgFileName
)) {
            System
.out
.println(DateUtils
.getStrDate()+" 本地文件已经存在:" + gpgFileName
);
            return;
        }
 
        
        SFTPUtil sftpUtil 
= this.initFtp();
        if (sftpUtil 
== null
) {
            writeErrorMsg("initFtp failed");
            return;
        }
 
        
        if (!sftpUtil
.isExistsFile(SFTPDirectory
, gpgFileName
)) {
            System
.out
.println(DateUtils
.getStrDate()+" 服务器上不存在文件:" + gpgFileName
);
            closeFtp(sftpUtil
);
            return;
        }
 
        if (!firstExistsFileFlag
) {
            System
.out
.println(DateUtils
.getStrDate()+" 第一次发现文件存在:" + gpgFileName
);
            firstExistsFileFlag 
= true;
            closeFtp(sftpUtil
);
            return;
        }
 
 
        
        String downloadFile 
= downloadFtpFiles(sftpUtil
, localFilePath
, gpgFileName
);
        System
.out
.println(DateUtils
.getStrDate()+" 下载文件:" + downloadFile
);
 
        if (downloadFile 
!= null
) {
            todayDownLoadFile 
= gpgFileName
;
            todayGpgFilePath 
= localFilePath 
+ "/" + gpgFileName
;
            todayCsvFilePath 
= downloadFile
;
 
            writeErrorMsg("今日文件下载完成:" + todayDownLoadFile
);
 
            firstExistsFileFlag 
= false;
            
            notifyService
.notifyFilesChanged(downloadFile
);
 
 
        }
 
        closeFtp(sftpUtil
);
    }
 
 
    private String 
downloadFtpFiles(SFTPUtil sftpUtil
, String localFilePath
, String fileName
) {
        String downloadFileName 
= null
;
        try {
            sftpUtil
.cd(SFTPDirectory
);
            sftpUtil
.download(SFTPDirectory
, fileName
, localFilePath 
+ "/" + fileName
);
 
            if (fileName
.endsWith(".xlsx")) {
                downloadFileName 
= localFilePath 
+ "/" + fileName
;
            }
 
 
            if (downloadFileName 
!= null
) {
                File file 
= new File(downloadFileName
);
                if (!file
.exists()) {
                    System
.out
.println("本地不存在" + downloadFileName
);
                    downloadFileName 
= null
;
                }
            }
 
 
        } catch (Exception e
) {
            e
.printStackTrace();
        }
 
 
        return downloadFileName
;
    }
 
 
    private SFTPUtil 
initFtp() {
        
        SFTPUtil sftp 
= new SFTPUtil(xiaomiFtpUser
, xiaomiFtpHost
, Integer
.valueOf(xiaomiFtpPort
),xiaomiPriKeyFile
);
        sftp
.login();
 
        System
.out
.println("login successed");
 
        return sftp
;
    }
 
    private void closeFtp(SFTPUtil sftp
) {
        try {
            sftp
.logout();
        } catch (Exception e
) {
            e
.printStackTrace();
        }
    }
 
    private boolean isLocalFileExists(String filePathName
) {
        File file 
= new File(filePathName
);
        if (file
.exists()) {
            return true;
        } else {
            return false;
        }
    }
 
    private String 
initLocalFilePath() {
        String filePath 
= XIAOMI_LOCAL_FilPath
;
        File file 
= new File(filePath
);
        file
.mkdirs();
        return filePath
;
    }
 
    private void writeErrorMsg(String msg
) {
        System
.out
.println(DateUtils
.date2FullStr(new Date()) + "=====" + msg
);
 
        errorLogService
.writeErrorLog("", msg
);
    }
}
 
4.定时任务调用
 
package com
.zqf
.cmbc
.task
;
 
import com
.zqf
.cmbc
.service
.CmbcFtpService
;
import com
.zqf
.cmbc
.service
.XiaoMiFtpService
;
import com
.zqf
.common
.utils
.DateUtils
;
import org
.springframework
.scheduling
.annotation
.Scheduled
;
import org
.springframework
.stereotype
.Component
;
 
import javax
.annotation
.Resource
;
 
@Component
public class SynXiaoMiFtpTask {
    @Resource
    XiaoMiFtpService xiaoMiFtpService
;
 
 
    
    @Scheduled(cron 
= "0 0/2 09 * * ? ")
    public void firsRrunTask() {
        System
.out
.println(DateUtils
.getStrDate() + " 小米第一次runTask");
 
        try {
            xiaoMiFtpService
.sync(1);
        } catch (Exception e
) {
            e
.printStackTrace();
        }
    }
 
}
 
5.配置文件
 
#小米sftp地址
xiaomi_ftp_host
=xxx
.com
xiaomi_ftp_user
=xxx
xiaomi_ftp_port
=2222
xiaomi_ftp_local_file_path
=/xmdata
#秘钥路径
xiaomi_prikey_file 
=/root
/xx
 
xiaomi_notify_host_url 
= http
://xx
.xx
.xx
.xx
.:8096/xx
/xx
/xx