File upload, download and delete operations on the FTP server

1. Add the latest commons-net package to the maven project:

        <!-- ftp上传文件 -->
        <dependency>
            <groupId>commons-net</groupId>
            <artifactId>commons-net</artifactId>
            <version>3.5</version>
        </dependency>

2、FTPUtil.java:

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

import java.io.*;

/**
 * Created by ssl on 2017/8/7.
 */
public class FTPUtil {
    /**
     * 上传文件(可供Action/Controller层使用)
     *
     * @param hostname    FTP服务器地址
     * @param port        FTP服务器端口号
     * @param username    FTP登录帐号
     * @param password    FTP登录密码
     * @param pathname    FTP服务器保存目录
     * @param fileName    上传到FTP服务器后的文件名称
     * @param inputStream 输入文件流
     * @return
     */
    public static boolean uploadFile(String hostname, int port, String username, String password, String pathname,
                                     String fileName, InputStream inputStream) throws Exception {
        boolean flag = false;
        FTPClient ftpClient = new FTPClient();
        ftpClient.setControlEncoding("UTF-8");
        try {
            //连接FTP服务器
            ftpClient.connect(hostname, port);
            //登录FTP服务器
            ftpClient.login(username, password);
            //是否成功登录FTP服务器
            int replyCode = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(replyCode)) {
                return flag;
            }
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftpClient.makeDirectory(pathname);
            ftpClient.changeWorkingDirectory(pathname);
            ftpClient.storeFile(fileName, inputStream);
            ftpClient.logout();
            flag = true;
        } catch (Exception e) {
            throw e;
        } finally {
            if (null != inputStream) {
                inputStream.close();
            }
            if (null != ftpClient) {
                ftpClient.disconnect();
            }
        }
        return flag;
    }

    /**
     * 上传文件(可对文件进行重命名)
     *
     * @param hostname       FTP服务器地址
     * @param port           FTP服务器端口号
     * @param username       FTP登录帐号
     * @param password       FTP登录密码
     * @param pathname       FTP服务器保存目录
     * @param filename       上传到FTP服务器后的文件名称
     * @param originfilename 待上传文件的名称(绝对地址)
     * @return
     */
    public static boolean uploadFileFromProduction(String hostname, int port, String username, String password,
                                                   String pathname, String filename, String originfilename) throws
            Exception {
        boolean flag = false;
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(new File(originfilename));
            flag = uploadFile(hostname, port, username, password, pathname, filename, inputStream);
        } catch (Exception e) {
            throw e;
        } finally {
            if (null != inputStream) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return flag;
    }

    /**
     * 上传文件(不可以进行文件的重命名操作)
     *
     * @param hostname       FTP服务器地址
     * @param port           FTP服务器端口号
     * @param username       FTP登录帐号
     * @param password       FTP登录密码
     * @param pathname       FTP服务器保存目录
     * @param originfilename 待上传文件的名称(绝对地址)
     * @return
     */
    public static boolean uploadFileFromProduction(String hostname, int port, String username, String password,
                                                   String pathname, String originfilename) {
        boolean flag = false;
        InputStream inputStream = null;
        try {
            String fileName = new File(originfilename).getName();
            inputStream = new FileInputStream(new File(originfilename));
            flag = uploadFile(hostname, port, username, password, pathname, fileName, inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != inputStream) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return flag;
    }


    /**
     * 删除文件
     *
     * @param hostname FTP服务器地址
     * @param port     FTP服务器端口号
     * @param username FTP登录帐号
     * @param password FTP登录密码
     * @param pathname FTP服务器保存目录
     * @param filename 要删除的文件名称
     * @return
     */
    public static boolean deleteFile(String hostname, int port, String username, String password, String pathname,
                                     String filename) {
        boolean flag = false;
        FTPClient ftpClient = new FTPClient();
        try {
            //连接FTP服务器
            ftpClient.connect(hostname, port);
            //登录FTP服务器
            ftpClient.login(username, password);
            //验证FTP服务器是否登录成功
            int replyCode = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(replyCode)) {
                return flag;
            }
            //切换FTP目录
            ftpClient.changeWorkingDirectory(pathname);
            ftpClient.dele(filename);
            ftpClient.logout();
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.logout();
                } catch (IOException e) {

                }
            }
        }
        return flag;
    }

    /**
     * 下载文件
     *
     * @param hostname  FTP服务器地址
     * @param port      FTP服务器端口号
     * @param username  FTP登录帐号
     * @param password  FTP登录密码
     * @param pathname  FTP服务器文件目录
     * @param filename  文件名称
     * @param localpath 下载后的文件路径
     * @return
     */
    public static boolean downloadFile(String hostname, int port, String username, String password, String pathname,
                                       String filename, String localpath) throws Exception {
        boolean success = false;
        OutputStream out = null;
        InputStream in = null;
        FTPClient ftp = new FTPClient();//org.apache.commons.net.ftp
        try {
            int reply;
            if (port > -1) {
                ftp.connect(hostname, port);
            } else {
                ftp.connect(hostname);//ftp默认的端口是21
            }
            //很多人写的是用ftp.getReplyCode()给获取连接的返回值,但是这样会导致storeFileStream返回null
            ftp.login(username, password);
            ftp.enterLocalActiveMode();
            ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                return success;
            }
            //切换目录 此处可以判断,切换失败就说明ftp上面没有这个路径(对路径名进行转码,解决中文乱码问题)
            boolean flag = ftp.changeWorkingDirectory(new String(pathname.getBytes(), FTP.DEFAULT_CONTROL_ENCODING));
            if (!flag) {
                throw new Exception("目录[" + pathname + "]不存在");
            }
            FTPFile[] fs = ftp.listFiles();
            for (int i = 0; i < fs.length; i++) {
                FTPFile ff = fs[i];
                if (!ff.getName().equals(new String(filename.getBytes(), FTP.DEFAULT_CONTROL_ENCODING))) {
                    continue;
                }
                String outFileName = ff.getName();
                //创建本地的文件时候要把编码格式转回来
                //String localFileName = new String(ff.getName().getBytes("ISO-8859-1"), "UTF-8");
                File localFile = new File(localpath.concat(File.separator).concat(filename));
                out = new FileOutputStream(localFile);
                in = ftp.retrieveFileStream(outFileName);
                byte[] byteArray = new byte[4096];
                int read = 0;
                while ((read = in.read(byteArray)) != -1) {
                    out.write(byteArray, 0, read);
                }
                //这句很重要 要多次操作这个ftp的流的通道,要等他的每次命令完成
                ftp.completePendingCommand();
                out.flush();
                ftp.logout();
                success = true;
            }
        } catch (Exception e) {
            throw e;
        } finally {
            if (null != out)
                out.close();
            if (null != in)
                in.close();
            if (ftp.isConnected()) {
                ftp.disconnect();
            }
        }
        return success;
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325881768&siteId=291194637