工具类 (一) 操作 ftp

依赖架包

<dependency>
	<groupId>commons-net</groupId>
	<artifactId>commons-net</artifactId>
	<version>3.6</version>
</dependency>

工具类

package com.chinamobile.util;

import java.io.*;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

public class FtpUtils {

    /**
     * @param path     上传到ftp服务器哪个路径下
     * @param addr     地址
     * @param port     端口号
     * @param username 用户名
     * @param password 密码
     * @return
     * @throws Exception
     */
    public static FTPClient connect(String path, String addr, int port, String username, String password) {
        FTPClient ftpClient = new FTPClient();
        int reply;
        try {
            ftpClient.connect(addr, port);
            ftpClient.login(username, password);
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            reply = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.disconnect();
                return null;
            }
            ftpClient.changeWorkingDirectory(path);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ftpClient;
    }

    /**
     * @param file 上传的文件或文件夹
     * @param path 上传的文件的路径
     * @return void
     * @throws :(Error   note)
     * @throws Exception
     * @author
     * @class ItemFtp
     * @title upload
     * @Description :
     * @time 2013 2013-11-27
     */
    public static void upload(File file, String path, FTPClient ftpClient) {

        System.out.println(" file.isDirectory() : " + file.isDirectory());

        try {
            if (file.isDirectory()) {
                ftpClient.changeWorkingDirectory(file.getName());
                String[] files = file.list();
                for (int i = 0; i < files.length; i++) {
                    File file1 = new File(file.getPath() + "\\" + files[i]);
                    if (file1.isDirectory()) {
                        upload(file1, path, ftpClient);
                        ftpClient.changeToParentDirectory();
                    } else {
                        File file2 = new File(file.getPath() + "\\" + files[i]);
                        FileInputStream input = new FileInputStream(file2);
                        ftpClient.storeFile(file2.getName(), input);
                        input.close();
                    }
                }
            } else {
                File file2 = new File(file.getPath());
                System.out.println(" file.getPath() : " + file.getPath() + " | file2.getName() : " + file2.getName());
                InputStream input = new FileInputStream(file2);
                ftpClient.storeFile(file2.getName(), input);
                input.close();  //关闭输入流
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * @param reomvepath 下载的文件的路径
     * @param fileName   下载的文件名
     * @param localPath  下载的文件本地路径
     * @return void
     * @throws :(Error   note)
     * @throws Exception
     * @author
     * @class ItemFtp
     * @title download
     * @Description : FPT 下载文件方法
     * @time 2013 2013-11-27
     */
    @SuppressWarnings("unused")
    public static void download(String reomvepath, String fileName, String localPath, FTPClient ftpClient) {
        try {
            ftpClient.changeWorkingDirectory(reomvepath);
            // 列出该目录下所有文件
            FTPFile[] fs = ftpClient.listFiles();
            // 遍历所有文件,找到指定的文件
            for (FTPFile ff : fs) {
                if (ff.getName().equals(fileName)) {
                    // 根据绝对路径初始化文件
                    File localFile = new File(localPath + "/" + ff.getName());
                    // 输出流
                    OutputStream is = new FileOutputStream(localFile);
                    // 下载文件
                    ftpClient.retrieveFile(ff.getName(), is);
                    System.out.println("下载成功!");
                    is.close();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
	/**
     * @param srcFname     被修改的文件
     * @param targetFname  修改成的文件名
     * @param ftpClient     ftp连接
     * @return
     */
    public static void renameFile(String srcFname,String targetFname,FTPClient ftpClient){
        if( ftpClient!=null ){
            try {
                ftpClient.rename(srcFname,targetFname);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
	/**
     * @param ftpClient     ftp连接
     * @return
     */
    public static void close(FTPClient ftpClient){
        if( ftpClient!=null ){
            try {
                if (ftpClient.isConnected()){
                    ftpClient.logout();  //退出连接
                    ftpClient.disconnect();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
    /**
     * 列出目录下的文件
     * @param directory 要列出的目录
     */
    public static FTPFile[] listFiles(FTPClient ftpClient, String directory) throws IOException {
            return ftpClient.listFiles(directory);

    }
    public static void delete(String path, String fileName, FTPClient ftpClient) throws IOException {
        ftpClient.changeWorkingDirectory(path);
        ftpClient.deleteFile(fileName);
    }

调用

    public String getStatementOfAccountFileFromFtp(String time) {
        FTPClient ftpClient = FtpUtils.connect(path, host, Integer.parseInt(port), username, password);
        String fileName=null;
        try {
            if (ftpClient != null) {
                //要下载的文件名?(事先无法确定)
                StringBuffer sb=new StringBuffer("M2M_WCDZ_");
                sb.append(time);
                //列出文件夹下的所有文件
                FTPFile[] fileList=FtpUtils.listFiles(ftpClient,path);
                for(int i=0;i<fileList.length;i++){
                    if(fileList[i].getName().startsWith(sb.toString())){
                        fileName=fileList[i].getName();
                        break;
                    }
                }
                if(!StringUtils.isEmpty(fileName)){
                    FtpUtils.download(path,fileName,localPath ,ftpClient);
                    //删除文件
                    FtpUtils.delete(path,fileName,ftpClient);
                }
            }
        } catch (Exception e) {
            logger.error("cmiot下载文件异常",e);
            e.printStackTrace();
        } finally {
            if(ftpClient != null){
                FtpUtils.close(ftpClient);
            }
        }

        return fileName;
    }

下一篇 工具类 (二) 操作 sftp