java之SFTP上传下载

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import java.util.Properties;

import com.jcraft.jsch.*;

/**
 * SFTP工具类
 */
public class SftpUtil {
    static Session sshSession = null;

    /**
     * 获取ChannelSftp
     */
    public static ChannelSftp getConnectIP(String host, String sOnlineSftpPort, String username, String password) {
        int port = 0;
        if (!("".equals(sOnlineSftpPort)) && null != sOnlineSftpPort) {
            port = Integer.parseInt(sOnlineSftpPort);
        }
        ChannelSftp sftp = null;
        try {
            JSch jsch = new JSch();
            jsch.getSession(username, host, port);
            sshSession = jsch.getSession(username, host, port);
            sshSession.setPassword(password);
            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");
            sshSession.setConfig(sshConfig);
            sshSession.connect();
            Channel channel = sshSession.openChannel("sftp");
            channel.connect();
            sftp = (ChannelSftp) channel;
        } catch (Exception e) {
            System.out.println("连接sftp失败");
            e.printStackTrace();
        }
        System.out.println("连接sftp成功");
        return sftp;
    }

    /**
     * 上传
     */
    public static void upload(String directory, String uploadFile, ChannelSftp sftp) {
        try {
            //检查路径
            if(!isExist(sftp, directory)){
                System.out.println("创建sftp服务器路径失败:" + directory);
                return;
            }
            sftp.cd(directory);
            File file = new File(uploadFile);
            sftp.put(new FileInputStream(file), file.getName());
            System.out.println("上传成功");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (sftp.isConnected()) {
                sshSession.disconnect();
                sftp.disconnect();
            }

        }
    }

    /**
     * 判断文件夹是否存在
     * true 目录创建成功,false 目录创建失败
     * @param sftp
     * @param filePath 文件夹路径
     * @return
     */
    public static boolean isExist(ChannelSftp sftp, String filePath) {
        String paths[] = filePath.split("\\/");
        String dir = paths[0];
        for (int i = 0; i < paths.length - 1; i++) {
            dir = dir + "/" + paths[i + 1];
            try{
                sftp.cd(dir);
            }catch(SftpException sException){
                if(sftp.SSH_FX_NO_SUCH_FILE == sException.id){
                    try {
                        sftp.mkdir(dir);
                    } catch (SftpException e) {
                        e.printStackTrace();
                        return false;
                    }
                }
            }
        }
        return true;
    }

    /**
     * 下载
     */
    public static void download(String directory, String downloadFile, String saveFile, ChannelSftp sftp) {
        try {
            String src = directory + "/" + downloadFile;
            String dst = saveFile + "/" + downloadFile;
            System.out.println("开始下载,sftp服务器路径:[" + src + "]目标服务器路径:[" + dst + "]");
            sftp.get(src, dst);
            System.out.println("下载成功");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (sftp.isConnected()) {
                sshSession.disconnect();
                sftp.disconnect();
            }

        }
    }

    /**
     * 查看
     */
    public static List<String> check(String directory, ChannelSftp sftp) {
        List<String> fileList = new ArrayList<>();
        try {
            sftp.cd(directory);
            ListIterator a = sftp.ls(directory).listIterator();
            while (a.hasNext()) {
                fileList.add((String) a.next());
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (sftp.isConnected()) {
                sshSession.disconnect();
                sftp.disconnect();
            }

        }
        return fileList;
    }

    /**
     * 删除
     */
    public static void delete(String directory, String deleteFile, ChannelSftp sftp) {
        try {
            sftp.cd(directory);
            sftp.rm(deleteFile);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (sftp.isConnected()) {
                sshSession.disconnect();
                sftp.disconnect();
            }

        }
    }


    public static void main(String[] args) {
        ChannelSftp ftp = getConnectIP("x.x.x.x", "21", "user", "pwd");
        // 上传
        upload("sftpFile/data", "E://456.docx", ftp);
        // 下载
        download("sftpFile/data", "456.docx", "D://", ftp);
    }


}

  

猜你喜欢

转载自www.cnblogs.com/651434092qq/p/12742985.html