java ftp 上传下载文件

java ftp 上传下载文件工具类

package antmap.web.oa.common;

import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.commons.lang.StringUtils;
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.*;
import java.nio.charset.StandardCharsets;


public class FtpUtils {
    //ftp服务器地址

    private String _hostname;
    //ftp服务器端口号默认为21
    private Integer _port = 21;
    //ftp登录账号
    private String _username;
    //ftp登录密码
    private String _password;
    private String _ftpDir;

    private FTPClient _ftpClient = null;

    /**
     * 构造函数
     */
    public FtpUtils() {
    //config下面的ftp.properties配置文件
          ResourceBundle resourceBundle = ResourceBundle.getBundle("config/ftp");
        _hostname = resourceBundle .getString("ftpServer");
        _port = Integer.parseInt(resourceBundle .getString("ftpPort"));
        _username = resourceBundle .getString("ftpUser");
        _password = resourceBundle .getString("ftpPsw");
        _ftpDir = resourceBundle .getString("ftpDir");
    }

    /**
     * 构造函数
     *
     * @param hostname ftp服务器IP
     * @param username ftp用户名
     * @param password ftp密码
     */
    public FtpUtils(String hostname, String username, String password) {
        _hostname = hostname;
        _username = username;
        _password = password;
    }

    /**
     * 构造函数
     *
     * @param hostname ftp服务器IP
     * @param port     ftp端口号
     * @param username ftp用户名
     * @param password ftp密码
     */
    public FtpUtils(String hostname, Integer port, String username, String password) {
        _hostname = hostname;
        _port = port;
        _username = username;
        _password = password;
    }


    /**
     * 初始化ftp服务器
     */
    private void initFtpClient() {
        _ftpClient = new FTPClient();
        try {
            Function.outMessage("connecting...ftp服务器:" + this._hostname + ":" + this._port);
            _ftpClient.connect(_hostname, _port); //连接ftp服务器
            _ftpClient.login(_username, _password); //登录ftp服务器
            int replyCode = _ftpClient.getReplyCode(); //是否成功登录服务器
            if (!FTPReply.isPositiveCompletion(replyCode)) {
                Function.outMessage("connect failed...ftp服务器:" + this._hostname + ":" + this._port);
            }
            Function.outMessage("connect successful...ftp服务器:" + this._hostname + ":" + this._port);
            if (FTPReply.isPositiveCompletion(_ftpClient.sendCommand("OPTS UTF8", "ON"))) {
                _ftpClient.setControlEncoding("utf-8");
            } else {
                _ftpClient.setControlEncoding("GBK");
            }

            if (!StringUtils.isBlank(this._ftpDir)) {
                _ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
                CreateDirecroty(_ftpDir);
                Function.outMessage("connect successful:" + this._ftpDir);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 上传文件
     *
     * @param pathname       ftp服务保存地址 文件夹
     * @param fileName       上传到ftp的文件名
     * @param originfilename 待上传文件的名称(绝对地址) *
     * @return 上传成功状态
     */
    public boolean uploadFile(String pathname, String fileName, String originfilename) {
        InputStream inputStream = null;
        try {
            Function.outMessage("开始上传文件");
            inputStream = new FileInputStream(new File(originfilename));
            initFtpClient();
            _ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            CreateDirecroty(pathname);
            _ftpClient.storeFile(fileName, inputStream);
            inputStream.close();
            _ftpClient.logout();
            Function.outMessage("上传文件成功");
        } catch (Exception e) {
            Function.outMessage("上传文件失败");
            e.printStackTrace();
        } finally {
            if (_ftpClient.isConnected()) {
                try {
                    _ftpClient.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != inputStream) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return true;
    }

    /**
     * 上传文件
     *
     * @param pathname    ftp服务保存地址 文件夹
     * @param fileName    上传到ftp的文件名
     * @param inputStream 输入文件流
     * @return boolean
     */
    public boolean uploadFile(String pathname, String fileName, InputStream inputStream) {
        boolean flag = false;
        try {
            Function.outMessage("开始上传文件");
            initFtpClient();
            _ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            CreateDirecroty(pathname);
            _ftpClient.storeFile(fileName, inputStream);
            inputStream.close();
            _ftpClient.logout();
            flag = true;
            Function.outMessage("上传文件成功");
        } catch (Exception e) {
            Function.outMessage("上传文件失败");
            e.printStackTrace();
        } finally {
            if (_ftpClient.isConnected()) {
                try {
                    _ftpClient.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != inputStream) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return flag;
    }

    /**
     * 改变目录路径
     *
     * @param directory 文件夹
     * @return boolean
     */
    private boolean changeWorkingDirectory(String directory) {
        boolean flag = true;
        try {
            flag = _ftpClient.changeWorkingDirectory(directory);
            if (flag) {
                Function.outMessage("进入文件夹" + directory + " 成功!");

            } else {
                Function.outMessage("进入文件夹" + directory + " 失败!开始创建文件夹");
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
        return flag;
    }

    /**
     * 创建多层目录文件,如果有ftp服务器已存在该文件,则不创建,如果无,则创建
     *
     * @param remote 远程连接主机
     * @throws IOException IOException
     */
    private void CreateDirecroty(String remote) throws IOException {
        String directory = remote + File.separator;
        // 如果远程目录不存在,则递归创建远程服务器目录
        if (!directory.equalsIgnoreCase(File.separator) && !changeWorkingDirectory(directory)) {
            int start = 0;
            int end;
            if (directory.startsWith(File.separator)) {
                start = 1;
            }
            end = directory.indexOf(File.separator, start);
            String path = "";
            StringBuilder paths;
            paths = new StringBuilder();
            do {
                String subDirectory = remote.substring(start, end);
                path = path + File.separator + subDirectory;
                if (!existFile(path)) {
                    if (makeDirectory(subDirectory)) {
                        changeWorkingDirectory(subDirectory);
                    } else {
                        Function.outMessage("创建目录[" + subDirectory + "]失败");
                        changeWorkingDirectory(subDirectory);
                    }
                } else {
                    changeWorkingDirectory(subDirectory);
                }
                paths.append(File.separator).append(subDirectory);
                start = end + 1;
                end = directory.indexOf(File.separator, start);
                // 检查所有目录是否创建完毕
            } while (end > start);
        }
    }

    /**
     * 判断ftp服务器文件是否存在
     *
     * @param path path
     * @return boolean
     * @throws IOException IOException
     */
    private boolean existFile(String path) throws IOException {
        boolean flag = false;
        FTPFile[] ftpFileArr = _ftpClient.listFiles(path);
        if (ftpFileArr.length > 0) {
            flag = true;
        }
        return flag;
    }

    /**
     * 创建目录
     *
     * @param dir dir
     * @return boolean
     */
    private boolean makeDirectory(String dir) {
        boolean flag = true;
        try {
            flag = _ftpClient.makeDirectory(dir);
            if (flag) {
                Function.outMessage("创建文件夹" + dir + " 成功!");

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

    /**
     * 下载文件 *
     *
     * @param pathname  FTP服务器文件目录 文件夹
     * @param filename  文件名称
     * @param localpath 下载后的文件路径
     * @return boolean
     */
    public boolean downloadFile(String pathname, String filename, String localpath) {
        boolean flag = false;
        OutputStream os = null;
        try {
            Function.outMessage("开始下载文件");
            initFtpClient();
            //切换FTP目录
            _ftpClient.changeWorkingDirectory(pathname);
            FTPFile[] ftpFiles = _ftpClient.listFiles();
            for (FTPFile file : ftpFiles) {
                if (filename.equalsIgnoreCase(file.getName())) {
                    File localFile = new File(localpath + File.separator + file.getName());
                    os = new FileOutputStream(localFile);
                    _ftpClient.retrieveFile(file.getName(), os);
                    os.close();
                }
            }
            _ftpClient.logout();
            flag = true;
            Function.outMessage("下载文件成功");
        } catch (Exception e) {
            Function.outMessage("下载文件失败");
            e.printStackTrace();
        } finally {
            if (_ftpClient.isConnected()) {
                try {
                    _ftpClient.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return flag;
    }

    /**
     * 下载文件到流
     *
     * @param pathname pathname
     * @return boolean
     * @date 2019-3-21 12:00
     * @author a
     */
    public boolean downloadFileSingleToOutputStream(String pathname, OutputStream os) throws IOException {
        boolean flag ;
        try {
            initFtpClient();
            _ftpClient.enterLocalPassiveMode();
            flag = _ftpClient.retrieveFile(pathname, os);
            _ftpClient.logout();
        } finally {
            if (_ftpClient.isConnected()) {
                _ftpClient.disconnect();
            }
        }
        return flag;
    }

    /**
     * 下载单个文件 *
     *
     * @param pathname  FTP服务器文件路径
     * @param localpath 下载后的文件路径
     * @return boolean
     */
    public boolean downloadFileSingle(String pathname, String localpath) {
        boolean flag = false;
        OutputStream os = null;
        try {
            Function.outMessage("开始下载文件");
            initFtpClient();
            File localFile = new File(localpath);
            os = new FileOutputStream(localFile);
            _ftpClient.enterLocalPassiveMode();
            flag = _ftpClient.retrieveFile(pathname, os);
            _ftpClient.logout();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (_ftpClient.isConnected()) {
                try {
                    _ftpClient.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (flag) {
                Function.outMessage("下载文件成功");
            } else {
                Function.outMessage("下载文件失败");
            }
        }
        return flag;
    }

    /**
     * 删除文件 *
     *
     * @param pathname FTP服务器保存目录 文件夹
     * @param filename 要删除的文件名称 *
     * @return boolean
     */
    public boolean deleteFile(String pathname, String filename) {
        boolean flag = false;
        try {
            Function.outMessage("开始删除文件");
            initFtpClient();
            //切换FTP目录
            _ftpClient.changeWorkingDirectory(pathname);
            _ftpClient.dele(filename);
            _ftpClient.logout();
            flag = true;
            Function.outMessage("删除文件成功");
        } catch (Exception e) {
            Function.outMessage("删除文件失败");
            e.printStackTrace();
        } finally {
            if (_ftpClient.isConnected()) {
                try {
                    _ftpClient.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return flag;
    }

    /**
     * 删除单个文件 *
     *
     * @param sPath FTP服务器保存文件路径
     * @return boolean
     */
    public boolean deleteFileSingle(String sPath) {
        boolean flag = false;
        try {
            Function.outMessage("开始删除文件");
            initFtpClient();
            _ftpClient.dele(sPath);
            _ftpClient.logout();
            flag = true;
            Function.outMessage("删除文件成功");
        } catch (Exception e) {
            Function.outMessage("删除文件失败");
            e.printStackTrace();
        } finally {
            if (_ftpClient.isConnected()) {
                try {
                    _ftpClient.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return flag;
    }

    /**
     * FPT上文件的复制
     *
     * @param olePath  原文件地址
     * @param newPath  新保存地址
     * @param fileName 文件名
     * @return boolean
     */
    public boolean copyFile(String olePath, String newPath, String fileName) {
        boolean flag = false;
        try {
            initFtpClient();
            // 跳转到文件目录
            _ftpClient.changeWorkingDirectory(olePath);
            //设置连接模式,不设置会获取为空
            _ftpClient.enterLocalPassiveMode();
            // 获取目录下文件集合
            FTPFile[] files = _ftpClient.listFiles();
            ByteArrayInputStream in ;
            org.apache.commons.io.output.ByteArrayOutputStream out ;
            for (FTPFile file : files) {
                // 取得指定文件并下载
                if (file.getName().equals(fileName)) {
                    //读取文件,使用下载文件的方法把文件写入内存,绑定到out流上
                    out = new ByteArrayOutputStream();
                    _ftpClient.retrieveFile(new String(file.getName().getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1), out);
                    in = new ByteArrayInputStream(out.toByteArray());
                    //创建新目录
                    CreateDirecroty(newPath);
                    //文件复制,先读,再写
                    //二进制
                    _ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
                    flag = uploadFile(newPath, fileName, in);
                    out.flush();
                    out.close();
                    in.close();
                }
            }
        } catch (Exception e) {
            Function.outMessage("复制已存在edb文件到备份文件夹失败!原因:" + e.getMessage());
        } finally {
            if (_ftpClient.isConnected()) {
                try {
                    _ftpClient.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return flag;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值