ftp和sftp两种协议备份文件和删除文件(本服务器和跨服务器)

2 篇文章 0 订阅

FTP协议传输——文件备份和删除

package com.kun.sq.util;


import com.kun.entity.po.dev.DpDevFtpServerPo;
import com.kun.framework.crypto.cipher.DesCipher;
import com.kun.portal.webframe.message.WebSocketUtil;
import com.kun.sq.constant.ResponseCode;
import com.kun.sq.dto.FileServerDto;
import com.kun.sq.service.ILifeCycleService;
import com.kun.web2db.utils.BaseResult;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.socket.WebSocketSession;

import java.io.*;
import java.net.SocketException;

/**
 * 简单操作FTP工具类 ,此工具类支持中文文件名,不支持中文目录
 * 如果需要支持中文目录,需要 new String(path.getBytes("UTF-8"),"ISO-8859-1") 对目录进行转码
 */
@Component
public class FTPUtil {

    // 日志工具
    private static Logger logger = Logger.getLogger(FTPUtil.class);
    // lifeCycleService
    @Autowired
    private ILifeCycleService lifeCycleService;

    /**
     * 获取FTPClient对象
     *
     * @param ftpHost     服务器IP
     * @param ftpPort     服务器端口号
     * @param ftpUserName 用户名
     * @param ftpPassword 密码
     * @return FTPClient
     */
    public FTPClient getFTPClient(String ftpHost, int ftpPort,
                                  String ftpUserName, String ftpPassword, WebSocketSession session) {

        FTPClient ftp = null;
        try {
            //解密
            ftpPassword = DesCipher.decrypt(ftpPassword);
            ftp = new FTPClient();
            // 连接FPT服务器,设置IP及端口
            ftp.connect(ftpHost, ftpPort);
            // 设置用户名和密码
            ftp.login(ftpUserName, ftpPassword);
            // 设置连接超时时间,5000毫秒
            ftp.setConnectTimeout(50000);
            // 设置中文编码集,防止中文乱码
            ftp.setControlEncoding("UTF-8");
            if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                logger.info("未连接到FTP,用户名或密码错误");
                WebSocketUtil.send(session, "未连接到FTP,用户名或密码错误");
                ftp.disconnect();
            } else {
                logger.info("FTP连接成功");
                WebSocketUtil.send(session, "FTP连接成功");
            }

        } catch (SocketException e) {
            e.printStackTrace();
            logger.info("FTP的IP地址可能错误,请正确配置");
            WebSocketUtil.send(session, "FTP的IP地址可能错误,请正确配置");
        } catch (IOException e) {
            e.printStackTrace();
            logger.info("FTP的端口错误,请正确配置");
            WebSocketUtil.send(session, "FTP的端口错误,请正确配置");
        }
        return ftp;
    }

    /**
     * 关闭FTP方法
     *
     * @param ftp ftp客户端
     * @return 关闭结果
     */
    public boolean closeFTP(FTPClient ftp) {

        try {
            ftp.logout();
        } catch (Exception e) {
            logger.error("FTP关闭失败");
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                    logger.error("FTP关闭失败");
                }
            }
        }

        return false;

    }


    /**
     * 下载FTP下指定文件
     *
     * @param ftp      FTPClient对象
     * @param filePath FTP文件路径
     * @param fileName 文件名
     * @param downPath 下载保存的目录
     * @return boolean
     */
    public boolean downLoadFTP(FTPClient ftp, String filePath, String fileName,
                               String downPath) {
        // 默认失败
        boolean flag = false;

        try {
            // 跳转到文件目录
            ftp.changeWorkingDirectory(filePath);
            // 获取目录下文件集合
            ftp.enterLocalPassiveMode();
            FTPFile[] files = ftp.listFiles();
            for (FTPFile file : files) {
                // 取得指定文件并下载
                if (file.getName().equals(fileName)) {
                    File downFile = new File(downPath + File.separator
                            + file.getName());
                    OutputStream out = new FileOutputStream(downFile);
                    // 绑定输出流下载文件,需要设置编码集,不然可能出现文件为空的情况
                    flag = ftp.retrieveFile(new String(file.getName().getBytes("UTF-8"), "ISO-8859-1"), out);
                    // 下载成功删除文件,看项目需求
                    // ftp.deleteFile(new String(fileName.getBytes("UTF-8"),"ISO-8859-1"));
                    out.flush();
                    out.close();
                    if (flag) {
                        logger.info("下载成功");
                    } else {
                        logger.error("下载失败");
                    }
                }
            }

        } catch (Exception e) {
            logger.error("下载失败");
        }

        return flag;
    }

    /**
     * FTP文件上传工具类
     *
     * @param ftp      ftp客户端
     * @param filePath 文件所在路径
     * @param ftpPath  备份地址
     * @return 上传结果
     */
    public boolean uploadFile(FTPClient ftp, String filePath, String ftpPath,WebSocketSession session) {

        boolean flag = false;
        InputStream in = null;
        try {
            // 设置PassiveMode传输
            ftp.enterLocalPassiveMode();
            //设置二进制传输,使用BINARY_FILE_TYPE,ASC容易造成文件损坏
            ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
            //判断FPT目标文件夹时候存在不存在则创建
            if (!ftp.changeWorkingDirectory(ftpPath)) {
                ftp.makeDirectory(ftpPath);
            }
            //跳转目标目录
            ftp.changeWorkingDirectory(ftpPath);

            //上传文件
            File file = new File(filePath);
            in = new FileInputStream(file);
            String tempName = ftpPath + File.separator + file.getName();
            flag = ftp.storeFile(new String(tempName.getBytes("UTF-8"), "ISO-8859-1"), in);
            if (flag) {
                logger.info("上传成功");
            } else {
                logger.error("上传失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            WebSocketUtil.send(session, String.format("备份失败:%s",e.getMessage()));
            logger.error("上传失败");
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                WebSocketUtil.send(session, String.format("备份失败:%s",e.getMessage()));
            }
        }
        return flag;
    }

    /**
     * FPT上文件的复制
     *
     * @param ftp           FTPClient对象
     * @param fileServerDto 数据传输对象
     * @return boolean
     */
    public boolean copyFile(FTPClient ftp, FileServerDto fileServerDto, WebSocketSession socketSession) {

        boolean flag = false;
        try {
            String oldPath = fileServerDto.getOriginalPath();
            //备份地址
            String backPath = fileServerDto.getBackPath();
            String fileName = fileServerDto.getFileName();
            String fileWildcard = fileServerDto.getFileWildcard();
            String cycle = fileServerDto.getCycle();
            WebSocketUtil.send(socketSession, String.format("文件原始路径为:%s\n 文件名为:%s\n 文件备份路径为:%s\n", oldPath, fileName, backPath));
            long days2DateStr = 0;
            if (!StringUtils.isEmpty(cycle)) {
                days2DateStr = TimeUtil.days2TimeStamp(Integer.parseInt(cycle));
            }
            String[] split = {};
            if (!StringUtils.isEmpty(fileWildcard)) {
                split = fileWildcard.split("\\.");
            }

            FTPClient ftpClient = null;

            //是否备份到当前服务器
            Boolean currentServer = fileServerDto.getCurrentServer();
            if (!currentServer) {
                //跨服务器id
                String backServerId = fileServerDto.getBackServerId();
                if (!StringUtils.isEmpty(backServerId)) {
                    WebSocketUtil.send(socketSession, String.format("此次备份为跨服务器备份,开始查询备份服务器信息,服务器id为:%s", backServerId));
                    BaseResult fileServerInfo = lifeCycleService.findFileServerInfo(backServerId);
                    if (ResponseCode.SUCCESS_CODE != fileServerInfo.getReCode()) {
                        WebSocketUtil.send(socketSession, String.format("备份服务器信息查询失败。失败信息为:%s", fileServerInfo.getReMsg()));
                        return false;
                    }
                    DpDevFtpServerPo serverInfo = (DpDevFtpServerPo) fileServerInfo.getReInfo();
                    //文件类型
                    String ip = serverInfo.getFtpIp();
                    int port = Integer.parseInt(serverInfo.getFtpPort());
                    String username = serverInfo.getUserName();
                    String password = serverInfo.getUserPwd();
                    //连接新服务器
                    ftpClient = getFTPClient(ip, port, username, password, socketSession);
                }

            }
            // 跳转到文件目录
            ftp.changeWorkingDirectory(oldPath);
            //设置连接模式,不设置会获取为空
            ftp.enterLocalPassiveMode();
            // 获取目录下文件集合
            FTPFile[] files = ftp.listFiles();
            ByteArrayInputStream in = null;
            ByteArrayOutputStream out = null;

            if ("自定义".equals(fileName)) {
                fileName = "";
            }
            for (FTPFile file : files) {
                //根据文件通配符匹配
                if (StringUtils.isEmpty(fileName) && split.length > 0 && file.getName().endsWith(split[1])) {
                    if (currentServer) {
                        //本服务器备份
                        //读取文件,使用下载文件的方法把文件写入内存,绑定到out流上
                        out = new ByteArrayOutputStream();
                        ftp.retrieveFile(new String(file.getName().getBytes("UTF-8"), "ISO-8859-1"), out);
                        in = new ByteArrayInputStream(out.toByteArray());
                        //创建新目录
                        ftp.makeDirectory(backPath);
                        //文件复制,先读,再写
                        //二进制
                        ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
                        flag = ftp.storeFile(backPath + File.separator + (new String(file.getName().getBytes("UTF-8"), "ISO-8859-1")), in);
                        out.flush();
                        out.close();
                        in.close();
                        if (flag) {
                            logger.info("备份成功");
                        } else {
                            logger.error("备份失败");
                        }
                    } else {
                        //跨服务器备份
                        boolean uploadResult = uploadFile(ftpClient, oldPath + "/" + file.getName(), backPath,socketSession);
                        if (uploadResult) {
                            logger.info("备份成功");
                        } else {
                            logger.info("备份失败");
                        }
                    }
                }

                // 根据文件名匹配
                if (file.getName().equals(fileName)) {

                    if (currentServer) {
                        //读取文件,使用下载文件的方法把文件写入内存,绑定到out流上
                        out = new ByteArrayOutputStream();
                        ftp.retrieveFile(new String(file.getName().getBytes("UTF-8"), "ISO-8859-1"), out);
                        in = new ByteArrayInputStream(out.toByteArray());
                        //创建新目录
                        ftp.makeDirectory(backPath);
                        //文件复制,先读,再写
                        //二进制
                        ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
                        flag = ftp.storeFile(backPath + File.separator + (new String(file.getName().getBytes("UTF-8"), "ISO-8859-1")), in);
                        out.flush();
                        out.close();
                        in.close();
                        if (flag) {
                            logger.info("转存成功");
                        } else {
                            logger.error("复制失败");
                        }
                    } else {
                        //跨服务器备份
                        boolean uploadResult = uploadFile(ftpClient, oldPath + "/" + file.getName(), backPath,socketSession);
                        if (uploadResult) {
                            logger.info("备份成功");
                        } else {
                            logger.info("备份失败");
                        }
                    }

                }
                //自定义周期备份
                long time = file.getTimestamp().getTime().getTime();
                if (StringUtils.isEmpty(fileName) && split.length > 0 && file.getName().endsWith(split[1]) && days2DateStr != 0 && days2DateStr < time) {

                    if (currentServer) {
                        //读取文件,使用下载文件的方法把文件写入内存,绑定到out流上
                        out = new ByteArrayOutputStream();
                        ftp.retrieveFile(new String(file.getName().getBytes("UTF-8"), "ISO-8859-1"), out);
                        in = new ByteArrayInputStream(out.toByteArray());
                        //创建新目录
                        ftp.makeDirectory(backPath);
                        //文件复制,先读,再写
                        //二进制
                        ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
                        flag = ftp.storeFile(backPath + File.separator + (new String(file.getName().getBytes("UTF-8"), "ISO-8859-1")), in);
                        out.flush();
                        out.close();
                        in.close();
                        if (flag) {
                            logger.info("备份成功");
                        } else {
                            logger.error("备份失败");
                        }
                    } else {
                        //跨服务器备份
                        boolean uploadResult = uploadFile(ftpClient, oldPath + "/" + file.getName(), backPath,socketSession);
                        if (uploadResult) {
                            logger.info("备份成功");
                        } else {
                            logger.info("备份失败");
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.error("复制失败");
        }
        return flag;
    }

    /**
     * 实现文件的移动,这里做的是一个文件夹下的所有内容移动到新的文件,
     * 如果要做指定文件移动,加个判断判断文件名
     * 如果不需要移动,只是需要文件重命名,可以使用ftp.rename(oleName,newName)
     *
     * @param ftp     ftp客户端
     * @param oldPath 文件原始路径
     * @param newPath 新路径
     * @return boolean
     */
    public boolean moveFile(FTPClient ftp, String oldPath, String newPath) {
        boolean flag = false;

        try {
            ftp.changeWorkingDirectory(oldPath);
            ftp.enterLocalPassiveMode();
            //获取文件数组
            FTPFile[] files = ftp.listFiles();
            //新文件夹不存在则创建
            if (!ftp.changeWorkingDirectory(newPath)) {
                ftp.makeDirectory(newPath);
            }
            //回到原有工作目录
            ftp.changeWorkingDirectory(oldPath);
            for (FTPFile file : files) {

                //转存目录
                flag = ftp.rename(new String(file.getName().getBytes("UTF-8"), "ISO-8859-1"), newPath + File.separator + new String(file.getName().getBytes("UTF-8"), "ISO-8859-1"));
                if (flag) {
                    logger.info(file.getName() + "移动成功");
                } else {
                    logger.error(file.getName() + "移动失败");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("移动文件失败");
        }
        return flag;
    }

    /**
     * 根据文件名删除文件
     *
     * @param ftp           ftp客户端
     * @param fileServerDto 数据传输对象
     * @return 删除结果
     */
    public boolean deleteByFileName(FTPClient ftp, FileServerDto fileServerDto) {

        boolean flag = false;
        try {
            String oldPath = fileServerDto.getOriginalPath();
            String fileName = fileServerDto.getFileName();
            String fileWildcard = fileServerDto.getFileWildcard();
            //字符通配符
            String[] split = {};
            if (!StringUtils.isEmpty(fileWildcard)) {
                split = fileWildcard.split("\\.");
            }
            //自定义周期清除
            String cycle = fileServerDto.getCycle();
            long days2DateStr = 0;
            if (!StringUtils.isEmpty(cycle)) {
                days2DateStr = TimeUtil.days2TimeStamp(Integer.parseInt(cycle));
            }

            // 跳转到文件目录
            ftp.changeWorkingDirectory(oldPath);
            //设置连接模式,不设置会获取为空
            ftp.enterLocalPassiveMode();
            // 获取目录下文件集合
            FTPFile[] files = ftp.listFiles();
            for (FTPFile file : files) {
                //删除匹配的文件
                if (split.length > 0 && file.getName().endsWith(split[1])) {
                    flag = ftp.deleteFile(new String(file.getName().getBytes("UTF-8"), "ISO-8859-1"));
                    continue;
                }
                //自定义周期删除
                long time = file.getTimestamp().getTime().getTime();
                if (split.length > 0 && file.getName().endsWith(split[1]) && days2DateStr > 0 && days2DateStr < time) {
                    flag = ftp.deleteFile(new String(file.getName().getBytes("UTF-8"), "ISO-8859-1"));
                    continue;
                }
                // 删除指定文件
                if (fileName.equals(file.getName())) {
                    flag = ftp.deleteFile(new String(file.getName().getBytes("UTF-8"), "ISO-8859-1"));
                    continue;
                }
            }

        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return flag;
    }

    /**
     * 删除FTP上指定文件夹下文件及其子文件方法,添加了对中文目录的支持
     *
     * @param ftp       FTPClient对象
     * @param FtpFolder 需要删除的文件夹
     * @return
     */
    public boolean deleteByFolder(FTPClient ftp, String FtpFolder) {
        boolean flag = false;
        try {
            ftp.changeWorkingDirectory(new String(FtpFolder.getBytes("UTF-8"), "ISO-8859-1"));
            ftp.enterLocalPassiveMode();
            FTPFile[] files = ftp.listFiles();
            for (FTPFile file : files) {
                //判断为文件则删除
                if (file.isFile()) {
                    ftp.deleteFile(new String(file.getName().getBytes("UTF-8"), "ISO-8859-1"));
                }
                //判断是文件夹
                if (file.isDirectory()) {
                    String childPath = FtpFolder + File.separator + file.getName();
                    //递归删除子文件夹
                    deleteByFolder(ftp, childPath);
                }
            }
            //循环完成后删除文件夹
            flag = ftp.removeDirectory(new String(FtpFolder.getBytes("UTF-8"), "ISO-8859-1"));
            if (flag) {
                logger.info(FtpFolder + "文件夹删除成功");
            } else {
                logger.error(FtpFolder + "文件夹删除成功");
            }

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("删除失败");
        }
        return flag;

    }

    /**
     * 遍历解析文件夹下所有文件
     *
     * @param folderPath 需要解析的的文件夹
     * @param ftp        FTPClient对象
     * @return
     */
    public boolean readFileByFolder(FTPClient ftp, String folderPath) {
        boolean flage = false;
        try {
            ftp.changeWorkingDirectory(new String(folderPath.getBytes("UTF-8"), "ISO-8859-1"));
            //设置FTP连接模式
            ftp.enterLocalPassiveMode();
            //获取指定目录下文件文件对象集合
            FTPFile files[] = ftp.listFiles();
            InputStream in = null;
            BufferedReader reader = null;
            for (FTPFile file : files) {
                //判断为txt文件则解析
                if (file.isFile()) {
                    String fileName = file.getName();
                    if (fileName.endsWith(".txt")) {
                        in = ftp.retrieveFileStream(new String(file.getName().getBytes("UTF-8"), "ISO-8859-1"));
                        reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
                        String temp;
                        StringBuffer buffer = new StringBuffer();
                        while ((temp = reader.readLine()) != null) {
                            buffer.append(temp);
                        }
                        if (reader != null) {
                            reader.close();
                        }
                        if (in != null) {
                            in.close();
                        }
                        //ftp.retrieveFileStream使用了流,需要释放一下,不然会返回空指针
                        ftp.completePendingCommand();
                        //这里就把一个txt文件完整解析成了个字符串,就可以调用实际需要操作的方法
                        System.out.println(buffer.toString());
                    }
                }
                //判断为文件夹,递归
                if (file.isDirectory()) {
                    String path = folderPath + File.separator + file.getName();
                    readFileByFolder(ftp, path);
                }
            }


        } catch (Exception e) {
            e.printStackTrace();
            logger.error("文件解析失败");
        }

        return flage;

    }

}


SFTP协议备份文件和删除文件

package com.kun.sq.util;

import com.jcraft.jsch.*;
import com.kun.framework.crypto.cipher.DesCipher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Vector;

@Component
public class SftpUtil {


    private Logger logger = LoggerFactory.getLogger(SftpUtil.class);

    /**
     * 连接sftp服务器
     *
     * @param host     主机
     * @param port     端口
     * @param username 用户名
     * @param password 密码
     * @return
     */
    public ChannelSftp connect(String host, int port, String username, String password) {
        ChannelSftp sftp = null;
        try {
            JSch jsch = new JSch();
            jsch.getSession(username, host, port);
            Session sshSession = jsch.getSession(username, host, port);
            System.out.println("Session created.");
            sshSession.setPassword(password);
            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");
            sshSession.setConfig(sshConfig);
            sshSession.connect();
            System.out.println("Session connected.");
            System.out.println("Opening Channel.");
            Channel channel = sshSession.openChannel("sftp");
            channel.connect();
            sftp = (ChannelSftp) channel;
            System.out.println("Connected to " + host + ".");
        } catch (Exception e) {
            e.printStackTrace();
            sftp = null;
        }
        return sftp;
    }

    public ChannelSftp connectSftp(Session sshSession) {
        ChannelSftp sftp = null;
        try {
            System.out.println("Session connected.");
            System.out.println("Opening Channel.");
            Channel channel = sshSession.openChannel("sftp");
            channel.connect();
            sftp = (ChannelSftp) channel;
        } catch (Exception e) {
            e.printStackTrace();
            sftp = null;
        }
        return sftp;
    }

    public void exec(Session sshSession, String command) {
        ChannelExec channelExec = null;
        try {
            System.out.println("Session connected.");
            System.out.println("Opening Channel.");
            Channel channel = sshSession.openChannel("exec");
            channelExec = (ChannelExec) channel;
            channelExec.setCommand(command);
            channelExec.connect();
        } catch (Exception e) {
            e.printStackTrace();
            channelExec = null;
        } finally {
            channelExec.disconnect();
        }
    }

    public Session getSession(String host, int port, String username, String password) {
        Session sshSession = null;
        try {
            //解密
            password = DesCipher.decrypt(password);
            JSch jsch = new JSch();
            jsch.getSession(username, host, port);
            sshSession = jsch.getSession(username, host, port);
            System.out.println("Session created.");
            sshSession.setPassword(password);
            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");
            sshSession.setConfig(sshConfig);
            sshSession.connect(1500);
            System.out.println("Session connected.");
            System.out.println("Opening Channel.");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sshSession;
    }

    /**
     * 上传文件
     *
     * @param directory  上传的目录
     * @param uploadFile 要上传的文件
     * @param sftp
     */
    public String upload(String directory, String uploadFile, ChannelSftp sftp) {
        try {
            if (!directory.equals("")) {
                sftp.cd(directory);
            }
            File file = new File(uploadFile);
            sftp.put(new FileInputStream(file), file.getName());
            System.out.println("上传完成");
            sftp.disconnect();
            sftp.getSession().disconnect();
            return "传输成功";
        } catch (Exception e) {
            e.printStackTrace();
            sftp.disconnect();
            try {
                sftp.getSession().disconnect();
            } catch (JSchException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            return "传输失败,请检查配置!";
        }
    }

    /**
     * 下载文件
     *
     * @param directory    下载目录
     * @param downloadFile 下载的文件
     * @param saveFile     存在本地的路径
     * @param sftp
     */
    public void download(String directory, String downloadFile,
                         String saveFile, ChannelSftp sftp) {
        try {
            sftp.cd(directory);
            File file = new File(saveFile);
            sftp.get(downloadFile, new FileOutputStream(file));
            sftp.disconnect();
            sftp.getSession().disconnect();
            System.out.println("download ok,session closed");
        } catch (Exception e) {
            sftp.disconnect();
            try {
                sftp.getSession().disconnect();
            } catch (JSchException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            e.printStackTrace();
        }
    }

    public List<String> read(String directory, String readFile, ChannelSftp sftp, String charSetName) {
        List<String> stringlist = new ArrayList<>();
        InputStream inputStream = null;
        try {
            sftp.cd(directory);
            inputStream = sftp.get(readFile);
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, charSetName));
            String line = null;
            line = br.readLine();
            while (line != null) {
                stringlist.add(line);
                line = br.readLine(); // 一次读入一行数据
            }
            br.close();
        } catch (SftpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringlist;
    }

    /**
     * 删除文件
     *
     * @param directory  要删除文件所在目录
     * @param deleteFile 要删除的文件
     * @param sftp
     */
    public void delete(String directory, String deleteFile, ChannelSftp sftp) {
        try {
            sftp.cd(directory);
            sftp.rm(deleteFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 列出目录下的文件
     *
     * @param directory 要列出的目录
     * @param sftp
     * @return
     * @throws SftpException
     */
    public Vector listFiles(String directory, ChannelSftp sftp)
            throws SftpException {
        return sftp.ls(directory);
    }

    /**
     * 将输入流的数据上传到sftp作为文件
     *
     * @param directory    上传到该目录
     * @param sftpFileName sftp端文件名
     * @param input        输入流
     * @throws SftpException
     * @throws Exception
     */
    public void upload(String directory, String sftpFileName, InputStream input, ChannelSftp sftp) throws SftpException, JSchException {
        try {
            sftp.cd(directory);
        } catch (SftpException e) {
            logger.warn("directory is not exist");
            sftp.mkdir(directory);
            sftp.cd(directory);
        }
        sftp.put(input, sftpFileName);
     /*   if (sftp.isConnected()) {
            sftp.disconnect();
        }
        if (sftp.getSession().isConnected()) {
            sftp.getSession().disconnect();
        }*/
        logger.info(String.format(">>>>>>file:[%s] is upload successful<<<<<<", sftpFileName));
    }




}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值