Java 操作SFTP文件工具栏

package com.xml.util;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.commons.io.IOUtils;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;

import org.apache.poi.ss.usermodel.Workbook;

import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpATTRS;
import com.jcraft.jsch.SftpException;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import com.kingdee.eas.util.app.DbUtil;
import com.kingdee.jdbc.rowset.IRowSet;

/**
 * sftp工具类
 * 
 * @author xxx
 * @date 2020-12-17
 * @time 下午3:57:44
 * @version 1.0
 */
public class SFTPUtils {

    private String host = ""; // 服务器连接ip
    private String username = ""; // 用户名
    private String password = ""; // 密码
    private int port = 22; // 端口号

    public SFTPUtils() {
    }

    public SFTPUtils(String host, int port, String username, String password) {
        this.host = host;
        this.username = username;
        this.password = password;
        this.port = port;
    }

    public SFTPUtils(String host, String username, String password) {
        this.host = host;
        this.username = username;
        this.password = password;
    }

    /**
     * 连接sshSession
     */
    public Session sshSession() {
        Session sshSession = null;
        JSch jsch = new JSch();
        while (true) {
            try {
                jsch.getSession(username, host, port);
                sshSession = jsch.getSession(username, host, port);
                sshSession.setPassword(password);
                // Properties sshConfig = new Properties();
                // sshConfig.put("StrictHostKeyChecking", "no");
                // sshSession.setConfig("kex", "diffie-hellman-group1-sha1");
                sshSession.setConfig("StrictHostKeyChecking", "no");
                // sshSession.setConfig("StrictHostKeyChecking", "no");
                // sshSession.setConfig(sshConfig);
                sshSession.connect();
                return sshSession;
            } catch (Exception e) {
                // TODO Auto-generated catch block
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                e.printStackTrace();

            }
        }
    }

    /**
     * sshSession通过sshSession连接ChannelSftp(SFTP)
     */
    public ChannelSftp connect(Session sshSession) {
        ChannelSftp sftp = null;
        Channel channel = null;
        while (true) {
            try {
                channel = sshSession.openChannel("sftp");
                channel.connect();
                sftp = (ChannelSftp) channel;
                Class cl = ChannelSftp.class;
                Field f1 =cl.getDeclaredField("server_version");
                f1.setAccessible(true);
                f1.set(sftp, 2); 
                sftp.setFilenameEncoding("gbk");
                return sftp;
            } catch (JSchException e) {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                sshSession = sshSession();
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SftpException e) {
                // TODO Auto-generated catch block
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                e.printStackTrace();
            } catch (SecurityException e) {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (NoSuchFieldException e) {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    /**
     * 关闭ChannelSftp,Session连接
     */
    public void disconnect(ChannelSftp sftp, Session sshSession) {
        if (sftp != null) {
            if (sftp.isConnected()) {
                sftp.disconnect();
            }
        }
        if (sshSession != null) {
            if (sshSession.isConnected()) {
                sshSession.disconnect();
            }
        }
    }

    /**
     * 批量获取XML文件流
     * 
     * @param remotPath
     *            :远程下载目录(以路径符号结束,可以为相对路径eg:/assess/sftp/jiesuan_2/2014/)
     * @param indexOfFileName
     *            :获取某一天的文件(yyyyMMdd)
     * @param indexOfFileNameXiaJi
     *            :获取某一天的文件下级文件夹res或者req或者什么文件夹名
     * @param ctx
     * 
     * @param yinhang
     *            :银行简称以_符号结束(BOC_)
     * @param sftp
     *            :
     * @param sshSession
     *            :
     * @return filenames :文件名称以及文件流 (Map<String, InputStream>)
     */
    public Map<String, InputStream> batchDownLoadFileXml(String remotePath,
            String indexOfFileName, String indexOfFileNameXiaJi,
            String yinhang, Context ctx, ChannelSftp sftp, Session sshSession) {
        Map<String, InputStream> filenames = new HashMap<String, InputStream>();
        ;
        Vector v = listFiles(remotePath, sftp);
        // sftp.cd(remotePath);
        if (v.size() > 0) {
            System.out.println("本次处理文件个数不为零,开始下载...fileSize=" + v.size());
            Iterator it = v.iterator();
            while (it.hasNext()) {
                LsEntry entry = (LsEntry) it.next();
                String filename = entry.getFilename();
                SftpATTRS attrs = entry.getAttrs();
                if (!attrs.isDir()) {
                    // boolean flag = false;

                    int lastIndexOf = 0;
                    if (filename.indexOf(indexOfFileName) != -1) {
                        // String localFileName = + filename;
                        remoteZipToFile(remotePath + filename, remotePath,
                                sshSession);
                        lastIndexOf = filename.lastIndexOf(".");
                        Vector v1 = listFiles(remotePath + indexOfFileName
                                + "/" + indexOfFileNameXiaJi, sftp);
                        // sftp.cd(remotePath);

                        if (v1.size() > 0) {
                            
                            Iterator it1 = v1.iterator();
                            List<String> allList = new ArrayList<String>();
                            List<String> dbList = dbList(remotePath,
                                    indexOfFileName, indexOfFileNameXiaJi,
                                    yinhang, "HIS\\|CUR\\", ctx, sshSession);
                            List<String> chaZhiList = null;
                            if (dbList != null) {
                                remoteZipToFileHouZhui(remotePath, indexOfFileName,
                                        indexOfFileNameXiaJi, "BAL", sshSession);
                                System.out.println("本次读取文件个数不为零,读取...fileSize="
                                        + v1.size());
                                while (it1.hasNext()) {
                                    LsEntry entry1 = (LsEntry) it1.next();
                                    String filename1 = entry1.getFilename();
                                    SftpATTRS attrs1 = entry1.getAttrs();
                                    if (!attrs1.isDir()) {
                                        int lastIndexOf1 = filename1
                                                .lastIndexOf(".");
                                        String suffix = filename1
                                                .substring(lastIndexOf1);
                                        if (suffix.toUpperCase().equals(".CUR")
                                                || suffix.toUpperCase().equals(
                                                        ".HIS")) {
                                            allList.add(filename1);

                                        }
                                    }
                                }
                            }
                            if ("res".equals(indexOfFileNameXiaJi)) {
                                chaZhiList = getNeedAddOpenList(allList, dbList);
                            } else {
                                chaZhiList = allList;
                            }
                            InputStream is = null;
                            String filename1 = null;
                            for (int i = 0; i < chaZhiList.size(); i++) {
                                filename1 = chaZhiList.get(i);
                                while (true) {
                                    try {
                                        is = sftp.get(remotePath
                                                + filename.substring(0,
                                                        lastIndexOf) + "/"
                                                + indexOfFileNameXiaJi + "/"
                                                + filename1);
                                        break;
                                    } catch (SftpException e) {
                                        // TODO Auto-generated catch block
                                        try {
                                            Thread.sleep(5000);
                                            sftp = connect(sshSession());
                                        } catch (Exception e1) {
                                            // TODO Auto-generated catch block
                                            e1.printStackTrace();
                                        }
                                        e.printStackTrace();
                                    }
                                }
                                // TODO 编码定义
                                BufferedReader bre;
                                try {
                                    bre = new BufferedReader(
                                            new InputStreamReader(is, "GBK"));

                                    StringBuffer a = new StringBuffer();
                                    String str = "";
                                    // 循环读取,一次读取一行
                                    while ((str = bre.readLine()) != null) {
                                        a.append(str);
                                    }

                                    if (a.indexOf("<?xml") < 0) {
                                        a
                                                .insert(0,
                                                        "<?xml version=\"1.0\" encoding=\"GBK\"?>");
                                    }
                                    String a1 = a.toString().replace("UTF-8",
                                            "GBK");
                                    a1 = a.toString().replace("utf-8", "GBK");
                                    is = new ByteArrayInputStream(a1.getBytes());
                                    filenames.put(filename1, is);
                                } catch (UnsupportedEncodingException e1) {
                                    // TODO Auto-generated catch block
                                    e1.printStackTrace();
                                } catch (IOException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                                try {
                                    is.close();

                                } catch (IOException e) {
                                    // TODO Auto-generated catch
                                    // block
                                    e.printStackTrace();
                                }
                            }
                        }
                        rm(remotePath + filename.substring(0, lastIndexOf),
                                sshSession);
                        break;
                    }

                }

            }
        }
        return filenames;
    }

    /**
     * 判断list差值 :
     * 
     * @return filenames :文件名称以及文件流 (Map<String, InputStream>)
     */
    public List<String> getNeedAddOpenList(List<String> allList,
            List<String> dbList) {
        if (dbList != null && !dbList.isEmpty()) {
            Map<String, String> dataMap = new HashMap<String, String>();
            for (String filename : dbList) {
                dataMap.put(filename, filename);

            }
            List<String> newList = new ArrayList<String>();
            for (String filename : allList) {
                if (!dataMap.containsKey(filename)) {
                    newList.add(filename);
                }
            }
            return newList;
        } else {
            return allList;

        }

    }

    /**
     * 判断list差值
     * 
     * @param remotPath
     *            :远程下载目录(以路径符号结束,可以为相对路径eg:/assess/sftp/jiesuan_2/2014/)
     * @param indexOfFileName
     *            :某一天的文件夹(yyyyMMdd)
     * @param indexOfFileNameXiaJi
     *            :某一天的文件夹下级文件夹res或者req或者什么文件夹名
     * @param houZhuiMing
     *            :文件后缀名HIS\|CUR\
     * @param sshSession
     *            : :文件名称以及文件流 (Map<String, InputStream>)
     */
    public List<String> dbList(String remotePath, String indexOfFileName,
            String indexOfFileNameXiaJi, String yinHang, String houZhuiMing,
            Context ctx, Session sshSession) {
        int i = 4;
        int dbSum = 0;
        String tiaojian2 = "SUBSTR(cfyinhangfilename,2" + i + ",8)";
        if ("CMBC_".equals(yinHang)) {
            i = 5;
            tiaojian2 = "SUBSTR(cfyinhangfilename,2" + (i + 1) + ",8)";
        } else if ("CIB_".equals(yinHang)) {
            tiaojian2 = "SUBSTR(cfyinhangfilename,2" + (i + 1) + ",8)";
        }
        List dbList = null;
        try {
            IRowSet irfileName = DbUtil.executeQuery(ctx,
                    "/*dialect*/ SELECT count(*) FROM CT_JIA_XMLFILENAME  where   SUBSTR(cfyinhangfilename,0,"
                            + i + ") = '" + yinHang + "'  and " + tiaojian2
                            + " ='" + indexOfFileName + "'  and CFzhuangtai = 1 ");
            while (irfileName.next()) {
                dbSum = irfileName.getInt(1);
            }
            if (dbSum != getHouZhuiMingFileSum(remotePath, indexOfFileName,
                    indexOfFileNameXiaJi, houZhuiMing, sshSession)) {
                dbList = new ArrayList();
                irfileName = DbUtil
                        .executeQuery(
                                ctx,
                                " /*dialect*/ SELECT SUBSTR(cfyinhangfilename,"+(i+ 1)+ ",100)  FROM CT_JIA_XMLFILENAME  where   SUBSTR(cfyinhangfilename,0,"
                                        + i + ") = '" + yinHang + "'  and "
                                        + tiaojian2 + " ='" + indexOfFileName
                                        + "' and CFzhuangtai = 1");
                while (irfileName.next()) {
                    dbList.add(irfileName.getString(1));
                }
                String logsql =" /*dialect*/ delete FROM CT_JIA_XMLLOG   where  cfyinhangfilename  in (SELECT cfyinhangfilename FROM CT_JIA_XMLFILENAME  " +
                "where   SUBSTR(cfyinhangfilename,0,"
                + i + ") = '" + yinHang + "'  and "
                + tiaojian2 + " ='" + indexOfFileName
                + "' and CFzhuangtai <>1 )" ;
                DbUtil.execute(
                        ctx,
                        logsql);
                
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                
                
                
                String filenamesql = " /*dialect*/ delete FROM CT_JIA_XMLFILENAME  where   SUBSTR(cfyinhangfilename,0,"
                    + i + ") = '" + yinHang + "'  and "
                    + tiaojian2 + " ='" + indexOfFileName
                    + "' and CFzhuangtai <>1 ";
                DbUtil.execute(
                        ctx,
                        filenamesql);
                return dbList;
            }else{
                return null;
                
            }
        } catch (BOSException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return dbList;

    }

    /**
     * 批量获取EXCEL文件流
     * 
     * @param remotPath
     *            :远程下载目录(以路径符号结束,可以为相对路径eg:/assess/sftp/jiesuan_2/2014/)
     * @param indexOfFileName
     *            :获取某一天的文件(yyyyMMdd)
     * @param indexOfFileNameXiaJi
     *            :获取某一天的文件下级文件夹res或者req或者什么文件夹名
     * @param ctx
     * 
     * @param yinhang
     *            :银行简称以_符号结束(BOC_)
     * @param sftp
     *            :
     * @param sshSession
     *            :
     * @return filenames :文件名称以及文件流 (Map<String, InputStream>)
     */
    public Map<String, Workbook> batchDownLoadFileexcel(String remotePath,
            String indexOfFileName, String indexOfFileNameXiaJi,
            ChannelSftp sftp, Session sshSession) {
        Map<String, Workbook> filenames = new HashMap<String, Workbook>();

        Vector v1 = listFiles(remotePath + "/" + indexOfFileName + "/"
                + indexOfFileNameXiaJi + "/", sftp);
        // remotePath +"/"+ indexOfFileName
        // + "/交易记录表");
        // /data/msxg
        // sftp.cd(remotePath);
        if (v1.size() > 0) {
            System.out.println("本次读取excel文件个数不为零,读取...fileSize=" + v1.size());
            Iterator it1 = v1.iterator();
            while (it1.hasNext()) {
                LsEntry entry1 = (LsEntry) it1.next();
                String filename1 = entry1.getFilename();
                SftpATTRS attrs1 = entry1.getAttrs();
                if (!attrs1.isDir()) {
                    int lastIndexOf1 = filename1.lastIndexOf(".");
                    String suffix = filename1.substring(lastIndexOf1);
                    if (suffix.toUpperCase().equals(".XLSX")
                            || suffix.toUpperCase().equals(".XLS")) {
                        // remotePath+filename.substring(0,
                        // lastIndexOf)+filename1;
                        InputStream is = null;
                        while (true) {
                            try {
                                is = sftp.get(// "/data/msxg/"+filename1);
                                        remotePath + "/" + indexOfFileName
                                                + "/" + indexOfFileNameXiaJi
                                                + "/" + filename1);
                                break;
                            } catch (SftpException e) {
                                // TODO Auto-generated catch block
                                try {
                                    Thread.sleep(5000);
                                    sftp = connect(sshSession());
                                } catch (Exception e1) {
                                    // TODO Auto-generated catch block
                                    e1.printStackTrace();
                                }
                                e.printStackTrace();
                            }
                        }
                        Workbook wb1 = null;
                        try {
                            wb1 = ExcelUtil.readExcel(filename1, is);
                        } catch (IOException e1) {
                            // TODO Auto-generated catch block
                            e1.printStackTrace();
                        }
                        filenames.put(filename1, wb1);

                        try {
                            is.close();

                        } catch (IOException e) {
                            // TODO Auto-generated catch
                            // block
                            e.printStackTrace();
                        }
                    }

                }
            }
        }
        return filenames;
    }

    /**
     * 批量下载文件
     * 
     * @param remotPath
     *            :远程下载目录(以路径符号结束,可以为相对路径eg:/assess/sftp/jiesuan_2/2014/)
     * @param localPath
     *            :本地保存目录(以路径符号结束,D:\Duansha\sftp\)
     * @param del
     *            :下载后是否删除sftp文件
     * @return
     */
    public List<String> batchDownLoadFile(String remotePath, String localPath,
            boolean del, ChannelSftp sftp) {
        List<String> filenames = new ArrayList<String>();
        // connect();
        Vector v = listFiles(remotePath, sftp);
        // sftp.cd(remotePath);
        if (v.size() > 0) {
            System.out.println("本次处理文件个数不为零,开始下载...fileSize=" + v.size());
            Iterator it = v.iterator();
            while (it.hasNext()) {
                LsEntry entry = (LsEntry) it.next();
                String filename = entry.getFilename();
                SftpATTRS attrs = entry.getAttrs();
                if (!attrs.isDir()) {
                    boolean flag = false;
                    String localFileName = localPath + filename;
                    // 三种情况
                    flag = downloadFile(remotePath, filename, localPath,
                            filename, sftp);
                    if (flag) {
                        filenames.add(localFileName);
                        if (flag && del) {
                            deleteSFTP(remotePath, filename, sftp);
                        }

                    }
                }
            }
        }

        return filenames;
    }

    /*
     * 远程下载目录(以路径符号结束)
     * 
     * @param remoteFileName :下载文件名
     * 
     * @param localPath :本地保存目录(以路径符号结束)
     * 
     * @param localFileName :保存文件名
     * 
     * @return
     */
    public boolean downloadFile(String remotePath, String remoteFileName,
            String localPath, String localFileName, ChannelSftp sftp) {
        FileOutputStream fieloutput = null;
        try {
            // sftp.cd(remotePath);
            File file = new File(localPath + "/" + localFileName);
            if (!file.isDirectory()) {
                mkdirs(localPath + localFileName);
            }
            fieloutput = new FileOutputStream(file);
            sftp.get(remotePath + remoteFileName, fieloutput);
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (SftpException e) {
            e.printStackTrace();
        } finally {
            if (null != fieloutput) {
                try {
                    fieloutput.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

    /**
     * 上传单个文件
     * 
     * @param remotePath
     *            :远程保存目录
     * @param remoteFileName
     *            :保存文件名
     * @param localPath
     *            :本地上传目录(以路径符号结束)
     * @param localFileName
     *            :上传的文件名
     * @return
     */
    public boolean uploadFile(String remotePath, String remoteFileName,
            String localPath, String localFileName, ChannelSftp sftp,
            Session sshSession) {
        FileInputStream in = null;
        try {
            createDir(remotePath, sftp, sshSession);
            File file = new File(localPath + localFileName);
            in = new FileInputStream(file);
            sftp.put(in, remoteFileName);
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (SftpException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

    /**
     * 批量上传文件
     * 
     * @param remotePath
     *            :远程保存目录
     * @param localPath
     *            :本地上传目录(以路径符号结束)
     * @param del
     *            :上传后是否删除本地文件
     * @return
     */
    public boolean bacthUploadFile(String remotePath, String localPath,
            boolean del, ChannelSftp sftp, Session sshSession) {
        try {
            connect(sshSession);
            File file = new File(localPath);
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                if (files[i].isFile()
                        && files[i].getName().indexOf("bak") == -1) {
                    if (this.uploadFile(remotePath, files[i].getName(),
                            localPath, files[i].getName(), sftp, sshSession)
                            && del) {
                        deleteFile(localPath + files[i].getName());
                    }
                }
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;

    }

    /**
     * 删除本地文件
     * 
     * @param filePath
     * @return
     */
    public boolean deleteFile(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            return false;
        }

        if (!file.isFile()) {
            return false;
        }
        boolean rs = file.delete();
        return rs;
    }

    /**
     * 创建目录
     * 
     * @param createpath
     * @return
     */
    public boolean createDir(String createpath, ChannelSftp sftp,
            Session sshSession) {
        try {
            if (isDirExist(createpath, sftp)) {
                sftp.cd(createpath);
                return true;
            }
            String pathArry[] = createpath.split("/");
            StringBuffer filePath = new StringBuffer("/");
            for (String path : pathArry) {
                if (path.equals("")) {
                    continue;
                }
                filePath.append(path + "/");
                if (isDirExist(filePath.toString(), sftp)) {
                    sftp.cd(filePath.toString());
                } else {
                    // 建立目录
                    sftp.mkdir(filePath.toString());
                    // 进入并设置为当前目录
                    sftp.cd(filePath.toString());
                }

            }
            sftp.cd(createpath);
            return true;
        } catch (SftpException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 判断目录是否存在
     * 
     * @param directory
     * @return
     */
    public boolean isDirExist(String directory, ChannelSftp sftp) {
        boolean isDirExistFlag = false;
        while (true) {
            try {

                SftpATTRS sftpATTRS = sftp.lstat(directory);
                isDirExistFlag = true;
                return sftpATTRS.isDir();

            } catch (Exception e) {
                if (e.getMessage().toLowerCase().equals("no such file")||e.getMessage().toLowerCase().equals("failure")) {
                    return isDirExistFlag = false;
                } else {
                    try {
                        e.printStackTrace();
                        Thread.sleep(5000);
                        sftp = connect(sshSession());
                    } catch (Exception e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                }
            }
        }

    }

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

    /**
     * 如果目录不存在就创建目录
     * 
     * @param path
     */
    public void mkdirs(String path) {
        File f = new File(path);

        String fs = f.getParent();

        f = new File(fs);

        if (!f.exists()) {
            f.mkdirs();
        }
    }

    // 需要注意的是当删除某一目录时,必须保证该目录下没有其他文件才能正确删除,否则将删除失败。
    public static void deleteFolder(File folder) throws Exception {
        if (!folder.exists()) {
            throw new Exception("文件不存在");
        }
        File[] files = folder.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    // 递归直到目录下没有文件
                    deleteFolder(file);
                } else {
                    // 删除
                    file.delete();
                }
            }
        }
        // 删除
        folder.delete();

    }

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

        while (true) {
            try {
                if (isDirExist(directory, sftp)) {
                    v = sftp.ls(directory);
                }
                return v;
            } catch (SftpException e) {
                // TODO Auto-generated catch block
                try {
                    Thread.sleep(5000);
                    sftp = connect(sshSession());
                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                e.printStackTrace();
            }

        }
    }

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    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 int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    /**
     * @Description:远程解压缩指定目录下的指定名字的文件
     * 
     * @param fileName
     *            :需要解压的文件名字
     * 
     * @param decpath
     *            :解压完成后的存放路径
     */
    public void remoteZipToFile(String fileName, String decpath,
            Session sshSession) {
        System.out.println("开始解压");
        runCmd("/data/rizhi/unzip-5.52/unzip -o " + fileName + "  -d /"
                + decpath + "/", sshSession);
        System.out.println("解压成功");

    }

    /**
     * @Description:远程删除目录
     * 
     * @param decpath
     *            :删除目录及以下文件
     */
    public void rm(String decpath, Session sshSession) {
        System.out.println("开始删除" + decpath);
        // out.println("rm -rf " + decpath);// 解压zip格式
        runCmd("rm -rf " + decpath, sshSession);
        System.out.println("删除" + decpath + "成功");
    }

    /**
     * 远程删除目录下后缀名为某个的文件
     * 
     * @param remotPath
     *            :远程下载目录(以路径符号结束,可以为相对路径eg:/assess/sftp/jiesuan_2/2014/)
     * @param indexOfFileName
     *            :某一天的文件夹(yyyyMMdd)
     * @param indexOfFileNameXiaJi
     *            :某一天的文件夹下级文件夹res或者req或者什么文件夹名
     * @param houZhuiMing
     *            :文件后缀名(BAL)
     * @param sshSession
     *            :
     * @return filenames :文件名称以及文件流 (Map<String, InputStream>)
     */
    public void remoteZipToFileHouZhui(String remotePath,
            String indexOfFileName, String indexOfFileNameXiaJi,
            String houZhuiMing, Session sshSession) {
        System.out.println("开始删除" + remotePath + indexOfFileName + "/"
                + indexOfFileNameXiaJi + " 目录下" + houZhuiMing + "文件 ");
        runCmd("find " + remotePath + indexOfFileName + "/"
                + indexOfFileNameXiaJi + " -name \"*." + houZhuiMing
                + "\" | xargs rm", sshSession);
        System.out.println("结束删除" + remotePath + indexOfFileName + "/"
                + indexOfFileNameXiaJi + " 目录下" + houZhuiMing + "文件,删除成功 ");
    }

    /**
     * 远程获取目录下后缀名为某几类类型的文件
     * 
     * @param remotPath
     *            :远程下载目录(以路径符号结束,可以为相对路径eg:/assess/sftp/jiesuan_2/2014/)
     * @param indexOfFileName
     *            :某一天的文件夹(yyyyMMdd)
     * @param indexOfFileNameXiaJi
     *            :某一天的文件夹下级文件夹res或者req或者什么文件夹名
     * @param houZhuiMing
     *            :文件后缀名HIS\|CUR\
     * @param sshSession
     *            :
     * @return fileSize :文件个数
     */
    public Integer getHouZhuiMingFileSum(String remotePath,
            String indexOfFileName, String indexOfFileNameXiaJi,
            String houZhuiMing, Session sshSession) {
        System.out.println("开始获取" + remotePath + indexOfFileName + "/"
                + indexOfFileNameXiaJi + " 目录下CUR,HIS文件个数 ");
        String fileSize = runCmd("find " + remotePath + indexOfFileName + "/"
                + indexOfFileNameXiaJi + " -type f -regex \".*\\.\\("
                + houZhuiMing + ")\"| wc -l", sshSession);
        System.out.println("结束获取" + remotePath + indexOfFileName + "/"
                + indexOfFileNameXiaJi + " 目录下CUR,HIS文件,个数为: " + fileSize);
        return Integer.parseInt(fileSize.trim());

    }

    /**
     * 执行linux代码; :
     * 
     * @return filenames :文件名称以及文件流 (Map<String, InputStream>)
     */
    public String runCmd(String cmd, Session sshSession) {
        ChannelExec channelExec = null;
        InputStream in = null;
        while (true) {
            try {

                channelExec = (ChannelExec) sshSession.openChannel("exec");
                in = channelExec.getInputStream();
                channelExec.setCommand(cmd);
                channelExec.connect();
                String s = IOUtils.toString(in, "UTF-8");
                System.out.println("结果:" + s);
                channelExec.disconnect();
                return s;
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return null;
            } catch (JSchException e) {
                sshSession = sshSession();
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取文件大小 :
     * 
     * @return filenames :文件名称以及文件流 (Map<String, InputStream>)
     */
    public long getFileSize(String srcSftpFilePath, ChannelSftp sftp) {
        while (true) {
            try {
                SftpATTRS sftpATTRS = sftp.lstat(srcSftpFilePath);
                long filesize = sftpATTRS.getSize();
                return filesize;
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                sftp = connect(sshSession());
            }
        }
    }

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值