ftp处理、获取文件上传到ftp

//获取文件上传到不同的ftp
    public int sendWorkIssueRuleCsv(String pro,CommonsMultipartFile csv_file) throws IOException {
        
            int returnvalue=0;
            List<String> proList = new ArrayList<String>();
            if(pro.equals("全国")){
                
            }else{
                Helper.Spliter(pro, ",", proList);
            }
            List<FtpDeployManager> list=ftpDeployManagerDao.selectFtpList(proList);
            if(list.size()>0){
                SimpleDateFormat df = new SimpleDateFormat("yyyyMM");
                for(FtpDeployManager manager : list){
                    String ftpip = manager.getFtp_ip();
                    String ftpport = manager.getFtp_port();
                    String ftpuser = manager.getFtp_user();
                    String ftppassword = manager.getFtp_password();
                    String ftpdirect = manager.getFtp_direct();
                    String mark = HiveDataUtil.getProMark(pro);
                    String childwikdir="/"+mark+"/rule_group/"+df.format(new Date());
                    FtpUtil ftpUtil = new FtpUtil(ftpip, Convert.toIntValue(ftpport), ftpuser, ftppassword, ftpdirect,childwikdir);
                    if (ftpUtil.CreateFTPConnect() != 0) {
                        logger.error("ftp连接失败!");
                        returnvalue = -1;
                    } else {
                        try  {
                            InputStream input = csv_file.getInputStream();
                            boolean flag = ftpUtil.upload("task_rule@" + df.format(new Date()) + ".xls", input);
                            if (flag) {
                                returnvalue = 1;
                            } else {
                                returnvalue = 0;
                            }
                            input.close();
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                   }
                }
            }
        return returnvalue;
    }

ftp 部署

public class FtpDeployManager implements Serializable{ //序列化
    

    private String province;//省份
    
    private String status;//状态
    
    private String ftp_ip;//ip地址
    
    private String ftp_port;//端口
    
    private String ftp_user;//用户名
    
    private String ftp_password;//密码
    
    private String ftp_direct;//指定路径
package com.icos.help;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketException;
import org.apache.commons.net.ftp.*;
import org.apache.log4j.Logger;

public class FtpUtil {

    private FTPClient ftp = new FTPClient();
    private String LOCAL_CHARSET = "GBK";
    private String ip = "";
    private int port = 0;
    private String user = "";
    private String password = "";
    private String workdir = "";
    private String childdir="";
    private static Logger logger = null;

    public FtpUtil(String ip, int port, String user, String password, String workdir) {
        this.ip = ip;
        this.port = port;
        this.user = user;
        this.password = password;
        this.workdir = workdir;
        logger = Logger.getLogger(FtpUtil.class);
    }
    public FtpUtil(String ip, int port, String user, String password, String workdir,String childdir) {
        this.ip = ip;
        this.port = port;
        this.user = user;
        this.password = password;
        this.workdir = workdir;
        this.childdir=childdir;
        logger = Logger.getLogger(FtpUtil.class);
    }
    

    public int CreateFTPConnect() {
        try {
            logger.info("connect ftpserver " + ip + " : " + port);
            if (port > 0) {
                ftp.connect(ip, port);

            } else {
                ftp.connect(ip);
            }

            if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                ftp.disconnect();
                logger.error(
                        "FTP server[" + ip + ":" + (port > 0 ? port : ftp.getDefaultPort()) + "] refused connection.");
                return -1;
            }
            logger.info("FTP server[" + ip + ":" + (port > 0 ? port : ftp.getDefaultPort()) + "] connection success.");
            // 开启服务器对UTF-8的支持,如果服务器支持就用UTF-8编码,否则就使用本地编码(GBK).
            if (FTPReply.isPositiveCompletion(ftp.sendCommand("OPTS UTF8", "ON"))) {
                LOCAL_CHARSET = "UTF-8";
            }
            logger.info("FTP CHARSET is " + LOCAL_CHARSET);
            ftp.setControlEncoding(LOCAL_CHARSET);// 个别ftp协商字符集会有问题,临时直接用utf8格式
            ftp.setRemoteVerificationEnabled(false);
            ftp.setFileType(FTP.BINARY_FILE_TYPE);// 设置传输的模式
            ftp.setBufferSize(1024 * 1024);
            if (!ftp.login(user, password)) {
                // logger.error("FTP login failure:" + ftp.getReplyString());
                logger.info(" Login FTP server[" + ip + ":" + (port > 0 ? port : ftp.getDefaultPort()) + "] failure : "
                        + ftp.getReplyString());
                ftp.logout();
                return -1;
            }
            if(childdir.length()>0)
            {
                CreateDirecroty(childdir);
                workdir=workdir+childdir;
            }
        
            logger.info(" Login FTP server[" + ip + ":" + (port > 0 ? port : ftp.getDefaultPort()) + "] success");
            if (!ftp.changeWorkingDirectory(workdir)) {
                logger.error("FTP change directory failure:" + workdir);
                ftp.logout();
                return -1;
            }

        } catch (Exception e) {
            logger.error("when connect to ftp exeption", e);
            return -1;
        }
        return 0;
    }

    public String[] GetAllFileList() {
        try {
            ftp.enterLocalPassiveMode();// 设置被动模式
            return ftp.listNames();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            logger.error("get ftp file list error:", e);
            // e.printStackTrace();
            return null;
        }
    }

    public void CheckFile(String filename) throws Exception {
        FTPFile[] fs = ftp.listFiles();
        if (fs != null && fs.length > 0) {
            for (int i = 0; i < fs.length; i++) {
                if (fs[i].getName().equals(filename)) {
                    ftp.deleteFile(fs[i].getName());
                    break;
                }
            }
        }
    }

    public boolean FtpUpload(String filename, InputStream in) {
        try {
            filename = new String(filename.getBytes("utf-8"), "iso-8859-1");
            CheckFile(filename);
            return ftp.storeFile(filename, in);

        } catch (Exception e) {
            return false;
        }

    }

    public int DownLoadToFile(String remoteFileName, String localFileName) {
        String ftpFileName = "";
        boolean flag = false;
        File file = new File(localFileName);
        if(!file.exists())
        {
            file.mkdirs();
        }
        file=new File(localFileName+"/"+remoteFileName);
        FileOutputStream out = null;
        try {
            ftp.enterLocalPassiveMode();// 设置被动模式
            // ftp.getControlEncoding()
            ftpFileName = new String(remoteFileName.getBytes(ftp.getControlEncoding()), "iso-8859-1");
            // 判断本地文件是否存在,如果存在并且长度小于FTP文件的长度时断点续传;反之新增
            FTPFile[] ftpfile = ftp.listFiles(ftpFileName);
            long size = 0;
            if (ftpfile == null) {
                // System.err.println("remote ftp file: " + remoteFileName + " not exist");
                logger.warn("remote ftp file:  " + remoteFileName + " not exist");
                return 1;
            }
            if (ftpfile.length == 0) {
                // System.err.println("remote ftp file: " + remoteFileName + " not exist");
                logger.warn("remote ftp file:  " + remoteFileName + " not exist");
                return 1;
            }
            size = ftpfile[0].getSize();
            boolean isexist = file.exists();
            if (isexist) {
                long localFileSize = file.length();
                if (localFileSize > size) {
                    logger.warn(
                            "download file: " + remoteFileName + " have exist in local and file size bigger than ftp");
                    return 3;
                }
                if (localFileSize == size) {
                    logger.info("download file: " + remoteFileName + " have exist in local");
                    return 2;
                }

            }
            ftp.enterLocalPassiveMode();// 设置被动模式
            out = new FileOutputStream(file);
            flag = ftp.retrieveFile(ftpFileName, out);
            out.flush();
            if (flag) {
                // System.out.println("download file: " + remoteFileName + " success");
                logger.info("download file: " + remoteFileName + " success");
                return 0;
            } else {
                return -1;
            }
        } catch (SocketException e) {
            logger.error("connect remote file:  " + remoteFileName + " failure:", e);
            // System.err.println("connect remote file: " + remoteFileName + " failure");
            // e.printStackTrace();
            CreateFTPConnect();
            return -2;
        } catch (IOException e) {
            logger.error("read remote file:  " + remoteFileName + " failure:", e);
            // System.err.println("read remote file: " + remoteFileName + " failure");
            // e.printStackTrace();
            return -1;
        } finally {
            try {
                if (null != out) {
                    out.close();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                logger.error("close file " + file + " failure:", e);
                // e.printStackTrace();
                return -1;
            }
        }

    }

    public String[] GetRemoteFileList(String patt) {
        try {
            ftp.enterLocalPassiveMode();// 设置被动模式
            String ftpFileName = new String(patt.getBytes(ftp.getControlEncoding()), "iso-8859-1");
            return ftp.listNames(ftpFileName);
            // return ftp.listNames();
        } catch (Exception e) {
            // System.err.println("GetRemoteFileList failure");
            logger.error("GetRemoteFileList failure:", e);
            // e.printStackTrace();
            return null;
        }
    }

    public boolean uploadFile(String fileName, InputStream input) {
        //boolean success = false;
        try {
            String newFileName = new String(fileName.getBytes("utf-8"), "iso8859-1");

            ftp.enterLocalPassiveMode();
            FTPFile[] fs = ftp.listFiles();
            if (fs != null && fs.length > 0) {
                for (int i = 0; i < fs.length; i++) {
                    if (fs[i].getName().equals(fileName)) {
                        ftp.deleteFile(fs[i].getName());
                        break;
                    }
                }
            }
            boolean ret = ftp.storeFile(newFileName, input);
            System.out.println(ret);
            ftp.logout();
            //success = true;
        } catch (IOException e) {
            logger.error("ftp upload file:" + fileName + " failure:\n" + e);
            return false;
        }
        logger.info("ftp upload file:" + fileName + " success");
        return true;
    }
    
    
    
    public boolean upload(String fileName, InputStream input) {
        //boolean success = false;
        try {
            String newFileName = new String(fileName.getBytes("utf-8"), "iso8859-1");

            ftp.enterLocalPassiveMode();
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            FTPFile[] fs = ftp.listFiles();
            if (fs != null && fs.length > 0) {
                for (int i = 0; i < fs.length; i++) {
                    if (fs[i].getName().equals(fileName)) {
                        ftp.deleteFile(fs[i].getName());
                        break;
                    }
                }
            }
            boolean ret = ftp.storeFile(newFileName, input);
            System.out.println(ret);
            ftp.logout();
            //success = true;
        } catch (IOException e) {
            logger.error("ftp upload file:" + fileName + " failure:\n" + e);
            return false;
        }
        logger.info("ftp upload file:" + fileName + " success");
        return true;
    }

    
    public boolean uploadCsvFile(String fileName, InputStream input) {
        boolean success = false;
        try {
            String newFileName = new String(fileName.getBytes("utf-8"), "iso8859-1");

            ftp.enterLocalPassiveMode();

            FTPFile[] fs = ftp.listFiles();
            if (fs != null && fs.length > 0) {
                for (int i = 0; i < fs.length; i++) {
                    if (fs[i].getName().equals(fileName)) {
                        ftp.deleteFile(fs[i].getName());
                        break;
                    }
                }
            }
            ftp.storeFile(newFileName, input);
            input.close();
            success = true;
        } catch (IOException e) {
            logger.error("ftp upload file:" + fileName + " failure:\n" + e);
        }
        logger.info("ftp upload file:" + fileName + " success");
        return success;
    }
    public void CloseFtp() {
        try {
            if (ftp.isConnected()) {
                ftp.disconnect();
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            // System.err.println("FTP Close failure:" + ftp.getReplyString());
            // e.printStackTrace();
            logger.error("FTP " + ftp.getReplyString() + " Close failure:", e);
        }
    }

    public void createDir(String dirname) {

        try {

            ftp.makeDirectory(dirname);

            System.out.println("在目标服务器上成功建立了文件夹: " + dirname);

        } catch (Exception ex) {

            System.out.println(ex.getMessage());

        }

    }

    // 创建多层目录文件,如果有ftp服务器已存在该文件,则不创建,如果无,则创建
    public boolean CreateDirecroty(String remote) throws IOException {
        boolean success = true;
        String directory = remote + "/";
//        String directory = remote.substring(0, remote.lastIndexOf("/") + 1);
        // 如果远程目录不存在,则递归创建远程服务器目录
        if (!directory.equalsIgnoreCase("/") && !changeWorkingDirectory(new String(directory))) {
            int start = 0;
            int end = 0;
            if (directory.startsWith("/")) {
                start = 1;
            } else {
                start = 0;
            }
            end = directory.indexOf("/", start);
            String path = "";
            String paths = "";
            while (true) {

                String subDirectory = new String(remote.substring(start, end).getBytes("GBK"), "iso-8859-1");
                path = path + "/" + subDirectory;

                if (makeDirectory(subDirectory)) {
                    changeWorkingDirectory(subDirectory);
                } else {
                    logger.debug("创建目录[" + subDirectory + "]失败");
                    changeWorkingDirectory(subDirectory);
                }

                paths = paths + "/" + subDirectory;
                start = end + 1;
                end = directory.indexOf("/", start);
                // 检查所有目录是否创建完毕
                if (end <= start) {
                    break;
                }
            }
        }
        return success;
    }

    // 改变目录路径
    public boolean changeWorkingDirectory(String directory) {
        boolean flag = true;
        try {
            flag = ftp.changeWorkingDirectory(directory);
            if (flag) {
                logger.debug("进入文件夹" + directory + " 成功!");

            } else {
                logger.debug("进入文件夹" + directory + " 失败!");
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
        return flag;
    }

    // 创建目录
    public boolean makeDirectory(String dir) {
        boolean flag = true;
        try {
            flag = ftp.makeDirectory(dir);
            if (flag) {
                logger.debug("创建文件夹" + dir + " 成功!");

            } else {
                logger.debug("创建文件夹" + dir + " 失败!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

}

 

posted on 2019-08-21 09:57  tanada  阅读(1183)  评论(0编辑  收藏  举报