FTPUtil工具类

package com.travelsky.govprod.hninoutps.ms.dat.util;

import com.travelsky.dss.sc.component.slf4j.ILoggerDecorate;
import com.travelsky.dss.sc.component.slf4j.LoggerDecoratorFactory;
import com.travelsky.govprod.hninoutps.ms.dat.constant.scan.OfLogCodeEnum;
import com.travelsky.util.StringUtil;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

import java.io.*;
import java.net.SocketException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;


/**
 * FTP工具类
 * @author yang
 */
public class FTPUtil {

    ILoggerDecorate loggerDecorator = LoggerDecoratorFactory.getLogger(getClass());
    //声明常量
    public static final int SIZE=1024;


    /**
     * 创建FTP连接
     * @param ip
     * @param user
     * @param password
     * @return
     */
    public FTPClient obtainFTPClient(String ip, String user, String password) {

        FTPClient ftpClient = new FTPClient();
        try {
            ftpClient.connect(ip);
            ftpClient.login(user, password);
            if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                loggerDecorator.info(OfLogCodeEnum.valueOf("FTP_USER_PASSWORD_ERROR"),"未连接到FTP,用户名或密码错误。");
                ftpClient.disconnect();
            } else {
                loggerDecorator.info(OfLogCodeEnum.valueOf("NORMAL_LOG"),"FTP连接成功");
            }
        } catch (SocketException e) {
            e.printStackTrace();
            loggerDecorator.info(OfLogCodeEnum.valueOf("FTP_IP_ERROR"),"FTP的IP地址可能错误,请正确配置。"+e.getMessage(),e);
        } catch (IOException e) {
            e.printStackTrace();
            loggerDecorator.info(OfLogCodeEnum.valueOf("FTP_PROTOCOL_ERROR"),"FTP的端口错误,请正确配置。"+e.getMessage(),e);
        }

        if (!ftpClient.isConnected()) {
            loggerDecorator.info(OfLogCodeEnum.valueOf("FTP_CONNECT_ERROR"),"--------------FTP连接失败----------------");
            ftpClient = null;
        }

        return ftpClient;
    }


    /**
     * 关闭ftp连接
     * @param ftpClient
     */
    public  void closeFtp(FTPClient ftpClient){
        if (ftpClient!=null && ftpClient.isConnected()) {
            try {
                ftpClient.logout();
                ftpClient.disconnect();
                loggerDecorator.info(OfLogCodeEnum.valueOf("NORMAL_LOG"),"FTP远程连接关闭成功");
            } catch (IOException e) {
                e.printStackTrace();
                loggerDecorator.info(OfLogCodeEnum.valueOf("FTP_CLOSE_ERROR"),"FTP远程连接关闭失败"+e.getMessage(),e);
            }
        }
    }


    /**
     * 遍历目录下载所有FTP文件下载
     * @param ftpClient
     * @param ftpPath
     *
     * @return
     */
    public List<String> downloadFtpFile(FTPClient ftpClient, String ftpPath) {
        //每个文件读取为一个字符串
        List<String> list=new ArrayList<String>();


        try {
            ftpClient.setControlEncoding("UTF-8"); // 中文支持
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftpClient.enterLocalPassiveMode();
            ftpClient.setBufferSize(1024);
            ftpClient.setFileType(2);
            // 切换目录:就是进入下载文件的目录
            if(!ftpClient.changeWorkingDirectory(ftpPath)){
                loggerDecorator.info(OfLogCodeEnum.valueOf("SAVE_TMPFILE_ERROR"),"进入FTP下载文件目录失败:"+ftpPath);
                return list;
            }else{
                FTPFile[] fileDic = ftpClient.listFiles();
                if(fileDic.length>0){
                    //遍历所有文件,下载所有文件
                    for(FTPFile f: fileDic){
                        //在临时目录下,创建本地文件
                        File localFile = new File(System.getProperty("java.io.tmpdir")+File.separator+ f.getName());
                        if(!localFile.exists()){
                            localFile.createNewFile();
                        }
                        //创建本地文件的输出流
                        FileOutputStream fos = new FileOutputStream(localFile);
                        //将服务器上的文件内容通过输出流fos写到本地文件中
                        boolean flag=ftpClient.retrieveFile(f.getName(), fos);
                        //如果下载成功就删除服务器上的文件
                        if(flag){
                            ftpClient.dele(f.getName());
                        }
                        //读取本地文件,变为一个字符串
                        FileReader reader = new FileReader(localFile);//定义一个fileReader对象,用来初始化BufferedReader
                        BufferedReader bReader = new BufferedReader(reader);//new一个BufferedReader对象,将文件内容读取到缓存
                        StringBuilder sb = new StringBuilder();//定义一个字符串缓存,将字符串存放缓存中
                        String s = "";
                        while ((s =bReader.readLine()) != null) {//逐行读取文件内容,不读取换行符和末尾的空格
                            sb.append(s + "\n");//将读取的字符串添加换行符后累加存放在缓存中
                        }
                        bReader.close();
                        String str = sb.toString();
                        //空的不加入
                        if(!StringUtil.isNullOrBlank(str)){
                            list.add(str);
                        }
                        //删除本地文件
                        localFile.delete();
                        //关闭流
                        fos.close();
                    }

                }else {
                    loggerDecorator.info(OfLogCodeEnum.valueOf("NORMAL_LOG"),"FTP上待下载的文件为空");
                    return list;
                }
            }


        } catch (FileNotFoundException e) {
            e.printStackTrace();
            loggerDecorator.info(OfLogCodeEnum.valueOf("FILE_NOFOUND_ERROR"),"没有找到" + ftpPath + "文件"+e.getMessage(),e);
        } catch (SocketException e) {
            e.printStackTrace();
            loggerDecorator.info(OfLogCodeEnum.valueOf("FTP_CONNECT_ERROR"),"连接FTP失败."+e.getMessage(),e);
        } catch (IOException e) {
            e.printStackTrace();
            loggerDecorator.info(OfLogCodeEnum.valueOf("READY_FILE_ERROR"),"文件读取错误。"+e.getMessage(),e);
        }
        return list;
    }




    /**
     * 保存文本内容到文件中
     * @param filePath   文件路径
     * @param content    文件内容
     * @param fileName    文件名
     */
    public   void saveContentToFile(String filePath,String fileName,String content){
        PrintWriter pw;
        try {
            File dir=new File(filePath);
            if(!dir.exists()){
                dir.mkdirs();
                loggerDecorator.info(OfLogCodeEnum.valueOf("NORMAL_LOG"),"本地保存文件的目录已创建!");
            }else{
                loggerDecorator.info(OfLogCodeEnum.valueOf("NORMAL_LOG"),"本地保存文件的目录已存在!");
            }
            File file=new File(filePath+ File.separator+fileName);
            if(!file.exists()){
                file.createNewFile();
            }
            pw = new  PrintWriter(file,"UTF-8");
            pw.println(content+"\r\n");
            pw.close();
            loggerDecorator.info(OfLogCodeEnum.valueOf("NORMAL_LOG"),"写出完毕");
        } catch (FileNotFoundException e) {
            loggerDecorator.info(OfLogCodeEnum.valueOf("FILE_NOFOUND_ERROR"),"saveContentToFile中找不到文件!"+e.getMessage(),e);
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            loggerDecorator.info(OfLogCodeEnum.valueOf("SPECIAL_CODE_ERROR"),"文本内容中有特别的字符集:"+e.getMessage(),e);
            e.printStackTrace();
        } catch (IOException e) {
            loggerDecorator.info(OfLogCodeEnum.valueOf("MKDIR_FILE_ERROR"),"保存文本内容到文件中,创建文件失败:"+e.getMessage(),e);
            e.printStackTrace();
        }

    }



    /**
     * 上传文件到FTP服务器的指定目录
     * @param ftpClient		客户端
     * @param uploadPath	上传的路径
     * @param saveFileName	上传后的文件名
     * @param srcFile		待上传的文件
     */
    public void uploadFile(FTPClient ftpClient,String uploadPath,
                           String saveFileName,File srcFile){
        FileInputStream fis = null;
        try {
            // 获取文件编码格式
            String code = getFileEncode(srcFile);
            // 根据编码格式解析文件
            if("asci".equals(code)){
                code = "GBK";
            }
            fis = new FileInputStream(srcFile);


            /**进入工作目录,如果多次进来就不设置了*/
            ftpClient.changeWorkingDirectory(uploadPath);
            ftpClient.setBufferSize(1024);
            ftpClient.setControlEncoding("UTF-8");
            ftpClient.enterLocalPassiveMode();
            //设置文件类型(二进制)
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            //保存
            ftpClient.storeFile(saveFileName, fis);
            loggerDecorator.info(OfLogCodeEnum.valueOf("NORMAL_LOG"),"上传文件成功");
            fis.close();

        } catch (FileNotFoundException e) {
            loggerDecorator.info(OfLogCodeEnum.valueOf("FILE_NOFOUND_ERROR"),"文件找不到异常"+e.getMessage(),e);
            e.printStackTrace();
        } catch (IOException e) {
            loggerDecorator.info(OfLogCodeEnum.valueOf("FILE_ERROR"),"文件异常:"+e.getMessage(),e);
            e.printStackTrace();
        }catch (Exception e) {
            loggerDecorator.info(OfLogCodeEnum.valueOf("FILE_ERROR"),"文件异常:"+e.getMessage(),e);
            e.getMessage();
            e.printStackTrace();
        }

    }




    /**
     * FTP服务器文件名转码方法
     * @param uncode
     * @return
     * @throws UnsupportedEncodingException
     */
    public  String encodeForFtp(String uncode) {
        String encode="FTP文件名转码失败";
        try {
            encode = new String(uncode.getBytes("GBK"),"ISO-8859-1");
        } catch (UnsupportedEncodingException e) {
            loggerDecorator.info(OfLogCodeEnum.valueOf("SPECIAL_CODE_ERROR"),"文本内容中有特别的字符集:"+e.getMessage(),e);
            e.printStackTrace();
        }
        return encode;
    }


    /**
     * properties文件转码
     *
     * @param uncode
     * @return
     */
    public  String encodeForProper(String uncode) {
        String encode="配置文件转码失败";
        try {
            encode = new String(uncode.getBytes("ISO-8859-1"),"UTF-8");
        } catch (UnsupportedEncodingException e) {
            loggerDecorator.info(OfLogCodeEnum.valueOf("CODE_TRANSFER_ERROR"),"配置文件转码失败"+e.getMessage(),e);
            e.printStackTrace();
        }
        return encode;
    }

    /**
     * 文本文件转码
     *
     * @param uncode
     * @return
     */
    public  String encodeForFile(String code,String uncode) {
        String encode="配置文件转码失败";
        try {
            encode = new String(uncode.getBytes(code),"UTF-8");
        } catch (UnsupportedEncodingException e) {
            loggerDecorator.info(OfLogCodeEnum.valueOf("CODE_TRANSFER_ERROR"),"配置文件转码失败"+e.getMessage(),e);
            e.printStackTrace();
        }
        return encode;
    }

    /**
     * 当前日期
     *
     * @return
     */
    public static String obtainCurrentTime(){

        SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd-HHmmss");

        return sdf.format(new Date());
    }


    /**
     * 获取文本的编码格式
     * @param file
     * @return
     */
    public  String getFileEncode(File file) {
        String charset ="asci";
        byte[] first3Bytes = new byte[3];
        BufferedInputStream bis = null;
        try {
            boolean checked = false;
            bis = new BufferedInputStream(new FileInputStream(file));
            bis.mark(0);
            int read = bis.read(first3Bytes, 0, 3);
            if (read == -1)
                return charset;
            if (first3Bytes[0] == (byte) 0xFF && first3Bytes[1] == (byte) 0xFE) {
                charset = "Unicode";//UTF-16LE
                checked = true;
            } else if (first3Bytes[0] == (byte) 0xFE && first3Bytes[1] == (byte) 0xFF) {
                charset = "Unicode";//UTF-16BE
                checked = true;
            } else if (first3Bytes[0] == (byte) 0xEF && first3Bytes[1] == (byte) 0xBB && first3Bytes[2] == (byte) 0xBF) {
                charset = "UTF8";
                checked = true;
            }
            bis.reset();
            if (!checked) {
                int len = 0;
                int loc = 0;
                while ((read = bis.read()) != -1) {
                    loc++;
                    if (read >= 0xF0)
                        break;
                    if (0x80 <= read && read <= 0xBF) //单独出现BF以下的,也算是GBK
                        break;
                    if (0xC0 <= read && read <= 0xDF) {
                        read = bis.read();
                        if (0x80 <= read && read <= 0xBF)
                            //双字节 (0xC0 - 0xDF) (0x80 - 0xBF),也可能在GB编码内
                            continue;
                        else
                            break;
                    } else if (0xE0 <= read && read <= 0xEF) { //也有可能出错,但是几率较小
                        read = bis.read();
                        if (0x80 <= read && read <= 0xBF) {
                            read = bis.read();
                            if (0x80 <= read && read <= 0xBF) {
                                charset = "UTF-8";
                                break;
                            } else
                                break;
                        } else
                            break;
                    }
                }
                //TextLogger.getLogger().info(loc + " " + Integer.toHexString(read));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException ex) {
                    loggerDecorator.info(OfLogCodeEnum.valueOf("BUFFERED_CLOSED_ERROR")," BufferedInputStream关闭失败!"+ex.getMessage(),ex);
                }
            }
        }
        return charset;
    }


    /**
     * 拼接文件名
     * @return
     */
    public  String connectFileName(){
        SimpleDateFormat sdf=new  SimpleDateFormat("yyyyMMdd");
        Calendar ca=Calendar.getInstance();
        ca.add(Calendar.DAY_OF_MONTH,-1);

        return "CDF"+sdf.format(ca.getTime())+"_ok.txt";
    }


}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值