java实现连接vsftpd服务器,上传,下载,删除。

核心代码如下:

package com.bh.service;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.apache.commons.net.PrintCommandListener;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.bh.common.ExceptionUtil;

/**
 * FTP服务工具类
 *
 * @author: Rodge @time: 2017年12月24日 下午23:02:37 @version: V1.0.0
 */
@Component
public class FTPUtilService {

    /** 日志对象 **/
    private static final Logger log = LoggerFactory.getLogger(FTPUtilService.class);

    /** FTP地址 **/
    @Value(value = "${ftp.ftp_address}")
    private String ftp_address;

    /** FTP端口 **/
    @Value(value = "${ftp.ftp_port}")
    private String ftp_port;

    /** FTP用户名 **/
    @Value(value = "${ftp.ftp_username}")
    private String ftp_username;

    /** FTP密码 **/
    @Value(value = "${ftp.ftp_password}")
    private String ftp_password;

    /** FTP基础目录 **/
    private static final String base_path = "";

    /** 本地字符编码 **/
    @Value(value = "${ftp.localCharset}")
    private String localCharset;

    /** FTP协议里面,规定文件名编码为iso-8859-1 **/
    @Value(value = "${ftp.serverCharset}")
    private String serverCharset;

    /** UTF-8字符编码 **/
    private static final String CHARSET_UTF8 = "UTF-8";

    /** OPTS UTF8字符串常量 **/
    private static final String OPTS_UTF8 = "OPTS UTF8";

    /** 设置缓冲区大小40M **/
    @Value(value = "${ftp.buffer_size}")
    private String buffer_size;

    /** FTPClient对象 **/
    private static FTPClient ftpClient = null;

    /**
     * 本地文件上传到FTP服务器
     *
     * @param ftpPath
     *            FTP服务器文件相对路径,例如:test/123
     * @param multipartFileIOS
     *            上传时前台传过来的multipartFile的文件输入流
     * @param fileName
     *            上传到FTP服务的文件名,例如:666.txt
     * @return boolean 成功返回true,否则返回false
     */
    public boolean uploadLocalFile(String ftpPath, InputStream multipartFileIOS, String fileName) {
        // 登录
        login(ftp_address, Integer.parseInt(ftp_port), ftp_username, ftp_password);
        boolean flag = false;
        if (ftpClient != null) {
            InputStream fis = null;
            try {
                fis = multipartFileIOS;
                ftpClient.setBufferSize(Integer.parseInt(buffer_size));
                // 设置编码:开启服务器对UTF-8的支持,如果服务器支持就用UTF-8编码,否则就使用本地编码(GBK)
                if (FTPReply.isPositiveCompletion(ftpClient.sendCommand(OPTS_UTF8, "ON"))) {
                    localCharset = CHARSET_UTF8;
                }
                ftpClient.setControlEncoding(localCharset);
                ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
                if (!base_path.isEmpty() || !ftpPath.isEmpty()) {
                    String path = changeEncoding(base_path + ftpPath);
                    // 目录不存在,则递归创建
                    if (!ftpClient.changeWorkingDirectory(path)) {
                        this.createDirectorys(path);
                    }
                }
                // 设置被动模式,开通一个端口来传输数据
                ftpClient.enterLocalPassiveMode();
                // 上传文件
                flag = ftpClient.storeFile(new String(fileName.getBytes(localCharset), serverCharset), fis);
                if (flag) {
                    System.out.println("文件上传成功");
                } else {
                    System.out.println("文件上传失败");
                }
            } catch (Exception e) {
                log.error("本地文件上传FTP失败", e);
                e.printStackTrace();
                ExceptionUtil.recordErrorMsg(e);
            } finally {
                IOUtils.closeQuietly(fis);
                closeConnect();
            }
        }
        return flag;
    }

    /**
     * 根据指定目录获取该目录下的文件名称
     *
     * @param ftpPath
     * @return
     */
    public List<String> getFileNameListByPath(String ftpPath) {
        List<String> fileList = new ArrayList<>();
        // 登录
        login(ftp_address, Integer.parseInt(ftp_port), ftp_username, ftp_password);
        if (ftpClient != null) {
            ftpClient.setBufferSize(Integer.parseInt(buffer_size));
            try {
                if (ftpPath != null && ftpPath != "") {
                    String path = changeEncoding(base_path + ftpPath);
                    // 判断是否存在该目录
                    if (!ftpClient.changeWorkingDirectory(path)) {
                        log.error(base_path + ftpPath + "该目录不存在");
                        return fileList;
                    }
                }
                ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
                ftpClient.enterLocalPassiveMode(); // 设置被动模式,开通一个端口来传输数据
                ftpClient.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));
                String[] fs = ftpClient.listNames();
                if (fs != null && fs.length > 0) {
                    for (String string : fs) {
                        fileList.add(new String(string.getBytes(serverCharset), localCharset));
                    }
                    return fileList;
                }
            } catch (Exception e) {
                e.printStackTrace();
                log.error("下载文件失败", e);
                ExceptionUtil.recordErrorMsg(e);
            } finally {
                closeConnect();
            }
        }
        return fileList;
    }

    /**
     * 下载指定文件到本地
     *
     * @param ftpPath
     *            FTP服务器文件相对路径,例如:test/123
     * @param fileName
     *            要下载的文件名,例如:test.txt
     * @param savePath
     *            保存文件到本地的路径,例如:D:/test
     * @return 成功返回true,否则返回false
     */
    public boolean downloadFile(String ftpPath, String fileName, String savePath) {
        // 登录
        login(ftp_address, Integer.parseInt(ftp_port), ftp_username, ftp_password);
        boolean flag = false;
        if (ftpClient != null) {
            // 设置缓冲区大小
            ftpClient.setBufferSize(Integer.parseInt(buffer_size));
            try {
                if (ftpPath != null && ftpPath != "") {
                    String path = changeEncoding(base_path + ftpPath);
                    // 判断是否存在该目录
                    if (!ftpClient.changeWorkingDirectory(path)) {
                        log.error(base_path + ftpPath + "该目录不存在");
                        return flag;
                    }
                }
                ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
                ftpClient.enterLocalPassiveMode(); // 设置被动模式,开通一个端口来传输数据
                ftpClient.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));
                String[] fs = ftpClient.listNames();
                // 判断该目录下是否有文件
                if (fs == null || fs.length == 0) {
                    log.error(base_path + ftpPath + "该目录下没有文件");
                    return flag;
                }
                for (String ff : fs) {
                    String ftpName = new String(ff.getBytes(serverCharset), localCharset);
                    if (ftpName.equals(fileName)) {
                        File file = new File(savePath + '/' + ftpName);
                        try (OutputStream os = new FileOutputStream(file)) {
                            flag = ftpClient.retrieveFile(ff, os);
                        } catch (Exception e) {
                            log.error(e.getMessage(), e);
                            e.printStackTrace();
                            ExceptionUtil.recordErrorMsg(e);
                        }
                        break;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                log.error("下载文件失败", e);
                e.printStackTrace();
                ExceptionUtil.recordErrorMsg(e);
            } finally {
                closeConnect();
            }
        }
        return flag;
    }

    /**
     * 获取ftp目录下所有文件
     *
     * @param ftpPath
     * @return
     */
    public FTPFile[] getAllFiles(String ftpPath) {
        // 登录
        login(ftp_address, Integer.parseInt(ftp_port), ftp_username, ftp_password);
        if (ftpClient != null) {
            try {
                ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
                String path = changeEncoding(base_path + ftpPath);
                // 判断是否存在该目录
                if (!ftpClient.changeWorkingDirectory(path)) {
                    log.error(base_path + ftpPath + "该目录不存在");
                    return null;
                }
                ftpClient.enterLocalPassiveMode(); // 设置被动模式,开通一个端口来传输数据
                FTPFile[] fs = ftpClient.listFiles();
//                FTPFileEntryParser
//                ftpClient.initiateListParsing("NETWARE",path);
//                ftpClient.setParserFactory(new OSSFTPFileEntryParserFactory());
//                FTPFile[] fs = ftpClient.listFiles("./", new FTPFileFilter() {
//                    @Override
//                    public boolean accept(FTPFile file) {
//                        // System.out.println(file.getName());
//                        return true;
//                    }
//                });
                System.out.println("fs.length" + fs.length);
                // 判断该目录下是否有文件
                if (fs == null || fs.length == 0) {
                    log.error(base_path + ftpPath + "该目录下没有文件");
                    return null;
                }
                return fs;
            } catch (IOException e) {
                log.error("获取文件失败", e);
            } finally {
                closeConnect();
            }
        }
        return null;
    }

    /**
     * 根据名称获取文件,以输入流返回
     *
     * @param ftpPath
     *            FTP服务器上文件相对路径,例如:test/123
     * @param fileName
     *            文件名,例如:test.txt
     * @return InputStream 输入流对象
     */
    public InputStream getInputStreamByName(String ftpPath, String fileName) {
        // 登录
        login(ftp_address, Integer.parseInt(ftp_port), ftp_username, ftp_password);
        InputStream input = null;
        if (ftpClient != null) {
            // 设置缓冲区大小
            ftpClient.setBufferSize(Integer.parseInt(buffer_size));
            try {
                String path = changeEncoding(base_path + ftpPath);
                // 判断是否存在该目录
                if (!ftpClient.changeWorkingDirectory(path)) {
                    log.error(base_path + ftpPath + "该目录不存在");
                    return input;
                }
                ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
                ftpClient.enterLocalPassiveMode(); // 设置被动模式,开通一个端口来传输数据
                ftpClient.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));
                String[] fs = ftpClient.listNames();
                // 判断该目录下是否有文件
                if (fs == null || fs.length == 0) {
                    log.error(base_path + ftpPath + "该目录下没有文件");
                    return input;
                }
                boolean fileIsExit = false;
                for (String ff : fs) {
                    String ftpName = new String(ff.getBytes(serverCharset), localCharset);
                    if (ftpName.equals(fileName)) {
                        input = ftpClient.retrieveFileStream(ff);
                        byte[] bytes = IOUtils.toByteArray(input);
                        input = new ByteArrayInputStream(bytes);
                        ftpClient.completePendingCommand();
                        fileIsExit = true;
                        break;
                    }
                }
                if (!fileIsExit) {
                    return input;
                }
            } catch (IOException e) {
                log.error("获取文件失败", e);
            } finally {
                closeConnect();
            }
        }
        return input;
    }

    /**
     * 删除指定文件
     *
     * @param filePathAndFileName
     *            文件相对路径,例如:test/123/test.txt
     * @return 成功返回true,否则返回false
     */
    public boolean deleteFile(String filePathAndFileName) {
        // 登录
        login(ftp_address, Integer.parseInt(ftp_port), ftp_username, ftp_password);
        boolean flag = false;
        if (ftpClient != null) {
            try {
                String path = changeEncoding(base_path + filePathAndFileName);
                ftpClient.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));
                flag = ftpClient.deleteFile(path);
            } catch (IOException e) {
                log.error("删除文件失败", e);
                e.printStackTrace();
                ExceptionUtil.recordErrorMsg(e);
            } finally {
                closeConnect();
            }
        }
        return flag;
    }

    /**
     * 连接FTP服务器
     *
     * @param address
     *            地址,如:127.0.0.1
     * @param port
     *            端口,如:21
     * @param username
     *            用户名,如:root
     * @param password
     *            密码,如:root
     */
    private void login(String address, int port, String username, String password) {
        ftpClient = new FTPClient();
        try {
            ftpClient.connect(address, port);
            ftpClient.login(username, password);
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            int reply = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                closeConnect();
                log.error("FTP服务器连接失败");
            }
            System.out.println("FTP登录成功");
        } catch (Exception e) {
            log.error("FTP登录失败", e);
        }
    }

    /**
     * 关闭FTP连接
     *
     */
    private void closeConnect() {
        if (ftpClient != null && ftpClient.isConnected()) {
            try {
                ftpClient.logout();
                ftpClient.disconnect();
            } catch (IOException e) {
                log.error("关闭FTP连接失败", e);
            }
        }
    }

    /**
     * FTP服务器路径编码转换
     *
     * @param ftpPath
     *            FTP服务器路径
     * @return String
     */
    private String changeEncoding(String ftpPath) {
        String directory = null;
        try {
            if (FTPReply.isPositiveCompletion(ftpClient.sendCommand(OPTS_UTF8, "ON"))) {
                localCharset = CHARSET_UTF8;
            }
            directory = new String(ftpPath.getBytes(localCharset), serverCharset);
        } catch (Exception e) {
            log.error("路径编码转换失败", e);
        }
        return directory;
    }

    /**
     * 在服务器上递归创建目录
     *
     * @param dirPath
     *            上传目录路径
     * @return
     */
    private void createDirectorys(String dirPath) {
        try {
            if (!dirPath.endsWith("/")) {
                dirPath += "/";
            }
            String directory = dirPath.substring(0, dirPath.lastIndexOf("/") + 1);
            ftpClient.makeDirectory("/");
            int start = 0;
            int end = 0;
            if (directory.startsWith("/")) {
                start = 1;
            } else {
                start = 0;
            }
            end = directory.indexOf("/", start);
            while (true) {
                String subDirectory = new String(dirPath.substring(start, end));
                if (!ftpClient.changeWorkingDirectory(subDirectory)) {
                    if (ftpClient.makeDirectory(subDirectory)) {
                        ftpClient.changeWorkingDirectory(subDirectory);
                    } else {
                        log.info("创建目录失败");
                        return;
                    }
                }
                start = end + 1;
                end = directory.indexOf("/", start);
                // 检查所有目录是否创建完毕
                if (end <= start) {
                    break;
                }
            }
        } catch (Exception e) {
            log.error("上传目录创建失败", e);
        }
    }
}

补充yml配置如下:

 #FTP登录 上传 下载相关配置
ftp:
  ftp_address: 192.163.20.155  
  ftp_port: 21
  ftp_username: bohua1
  ftp_password: BHsoft13579!
  localCharset: UTF-8
  serverCharset: ISO-8859-1
  buffer_size: 42680320

猜你喜欢

转载自blog.csdn.net/huxiaochao_6053/article/details/83616454