java操作ftp

java远程连接ftp,保存在ftp文件夹下的文件编码格式为iso-8859-1,在下载文件的时候需要将文件名进行编码查询,否则无法查询到文件

连接模式:

              1.主动模式:服务器连接到客户端的端口,

              2.被动模式:客户端连接到服务器的端口

package com.xinhua.common.untils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

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.yfntech.framework.excel.exception.FrameExcelException;

/**
* @author minqiang
* @Date 2018年11月16日 上午9:25:43
* ftp工具类  远程ftp服务器处理文件上传、下载
*/
public class FtpUtil {
    protected static final Logger logger = LoggerFactory.getLogger(FtpUtil.class);
    
    //ftp服务器地址
    public String hostName;
    //ftp服务器端口号默认为21
    public Integer port = 21;
    //ftp登录账号
    public String username; 
    //ftp登录密码
    public String password; 
    
    public FTPClient ftpClient = null;
    
    /**
     * 初始化ftp登录参数
     */
    public void initLoginParams() {
        InputStream in = null;
        try {
            Properties properties = new Properties();
            in = FtpUtil.class.getClassLoader().getResourceAsStream("ftp.properties");
            properties.load(in);
            this.hostName = properties.getProperty("ftp.hostName");
            this.username = properties.getProperty("ftp.username");
            this.password = properties.getProperty("ftp.password");
            this.port = Integer.parseInt(properties.getProperty("ftp.port"));
        } catch (IOException e) {
            logger.error("加载数据异常:" + e);
            throw new FrameExcelException(e);
        } finally {
            closeStream(null ,in);
        }
    }
    
    /**
     * 连接FTP服务器
     */
    public void connectFtpServer() {
        try {
            initLoginParams();
            logger.info("connecting...ftp服务器:" + this.hostName + ":"+ this.port);
            ftpClient = new FTPClient();
            //连接ftp服务器
            ftpClient.connect(hostName, port);
            //登录ftp服务器
            ftpClient.login(username, password); 
            //是否成功登录服务器
            int replyCode = ftpClient.getReplyCode();
            //ftpClient.enterLocalActiveMode();
            //被动模式连接
            ftpClient.enterLocalPassiveMode();
            //设置文件类型为二进制
            ftpClient.setFileType(ftpClient.BINARY_FILE_TYPE);
            if(!FTPReply.isPositiveCompletion(replyCode)){
                logger.info("connect failed...ftp服务器:" + this.hostName + ":" + this.port);
            }
            logger.info("connect success ftp服务器:" + this.hostName + ":" + this.port);
        }catch (MalformedURLException e) { 
           logger.error("初始化FTP异常:" + e);
           throw new FrameExcelException(e);
        }catch (IOException e) { 
           logger.error("初始化FTP异常:" + e);
           throw new FrameExcelException(e);
        } 
    }
    
    /**
     * 上传文件
     * @param pathName ftp服务保存地址
     * @param fileName 上传到ftp的文件名
     * @param inputStream 上传文件的读取流
     * @return 文件上传的状态信息 true-上传成功 false-上传失败
     */
    public boolean uploadFile(String pathName, String fileName, InputStream inputStream){
        boolean flag = false;
        try{
            logger.info("开始上传文件");
            connectFtpServer();
            //中文支持
            ftpClient.setControlEncoding("utf-8");
            createDirecroty(pathName);
            ftpClient.makeDirectory(pathName);
            //设置上传的路径
            ftpClient.changeWorkingDirectory(pathName);
            //FTP协议里面,规定文件名编码为iso-8859-1,所以目录名或文件名需要转码
            fileName = new String(fileName.getBytes("GBK"), "iso-8859-1");
            boolean storeFile = ftpClient.storeFile(fileName, inputStream);
            if (storeFile) {
                inputStream.close();
                ftpClient.logout();
                flag = true;
                logger.info("上传文件成功");
            } else {
                logger.info("上传文件失败");
            }
        } catch (Exception e) {
            logger.error("上传文件失败" + e);
            throw new FrameExcelException(e);
        } finally {
            closeStream(null ,inputStream);
            closeFtp();
        }
        return flag;
    }
    
    /**
     * 改变目录路径
     * @param directory
     * @return
     */
    public boolean changeWorkingDirectory(String directory) {
        boolean flag = true;
        try {
            flag = ftpClient.changeWorkingDirectory(directory);
            if (flag) {
                logger.info("进入文件夹" + directory + " 成功!");
            } else {
                logger.info("进入文件夹" + directory + " 失败!开始创建文件夹");
            }
        } catch (IOException ioe) {
            logger.error("改变目录路径异常:" + ioe);
            throw new FrameExcelException(ioe);
        }
        return flag;
    }

    /**
     * 创建多层目录文件,如果有ftp服务器已存在该文件,则不创建,如果无,则创建
     * @param remote
     * @return true-创建成功 false-创建失败
     * @throws IOException
     */
    public boolean createDirecroty(String remote) throws IOException {
        boolean success = true;
        String directory = remote + "/";
        // 如果远程目录不存在,则递归创建远程服务器目录
        if (!directory.equalsIgnoreCase("/") && !changeWorkingDirectory(new String(directory))) {
            int start = 0;
            int end = 0;
            if (directory.startsWith("/")) {
                start = 1;
            } else {
                start = 0;
            }
            end = directory.indexOf("/", start);
            String path = "";
            String paths = "";
            while (true) {
                String subDirectory = new String(remote.substring(start, end).getBytes("GBK"), "iso-8859-1");
                path = path + "/" + subDirectory;
                if (!existFile(path)) {
                    if (makeDirectory(subDirectory)) {
                        changeWorkingDirectory(subDirectory);
                    } else {
                        logger.info("创建目录[" + subDirectory + "]失败");
                        changeWorkingDirectory(subDirectory);
                    }
                } else {
                    changeWorkingDirectory(subDirectory);
                }

                paths = paths + "/" + subDirectory;
                start = end + 1;
                end = directory.indexOf("/", start);
                // 检查所有目录是否创建完毕
                if (end <= start) {
                    break;
                }
            }
        }
        return success;
    }

    /**
     * 判断ftp服务器文件是否存在   
     * @param path
     * @return
     * @throws IOException
     */
    public boolean existFile(String path) throws IOException {
        boolean flag = false;
        FTPFile[] ftpFileArr = ftpClient.listFiles(path);
        if (ftpFileArr.length > 0) {
            flag = true;
        }
        return flag;
    }
    
    /**
     * 创建目录
     * @param dir
     * @return
     */
    public boolean makeDirectory(String dir) {
        boolean flag = true;
        try {
            flag = ftpClient.makeDirectory(dir);
            if (flag) {
                logger.info("创建文件夹" + dir + " 成功!");
            } else {
                logger.info("创建文件夹" + dir + " 失败!");
            }
        } catch (Exception e) {
            logger.error("创建目录异常:" + e);
            throw new FrameExcelException(e);
        }
        return flag;
    }
    
    /**
    * 下载文件
    * @param pathname FTP服务器文件目录 
    * @param filename 文件名称
    * @return 下载的文件
    */
    public Map<String, InputStream> downloadFile(String pathname, String filename){ 
        Map<String, InputStream> fileMap = new HashMap<String, InputStream>();
        try { 
            logger.info("开始下载文件");
            connectFtpServer();
            //切换FTP目录 
            ftpClient.changeWorkingDirectory(pathname);
            ftpClient.setControlEncoding("GBK");
            FTPFile[] ftpFiles = ftpClient.listFiles(); 
            for(FTPFile file : ftpFiles){
                String ftpFilename = file.getName();
                ftpFilename = ftpFilename.substring(0, ftpFilename.lastIndexOf("."));
                if(filename.equalsIgnoreCase(ftpFilename)){
                    String fileName = new String(file.getName().getBytes("GBK"), "iso-8859-1");
                    InputStream in = ftpClient.retrieveFileStream(fileName);
                    fileMap.put(file.getName(), in);
                    logger.info("下载文件成功");
                } 
            } 
            ftpClient.logout();
        } catch (Exception e) { 
            logger.error("下载文件失败:" + e);
            throw new FrameExcelException(e);
        } finally { 
            closeFtp(); 
        } 
        return fileMap;
    }
    
    /**
     * 删除文件
     * @param pathname FTP服务器保存目录
     * @param filename 要删除的文件名称
     * @return 删除成功标志
     */
    public boolean deleteFile(String pathname, String filename){ 
        boolean flag = false; 
        try { 
            logger.info("开始删除文件");
            connectFtpServer();
            //切换FTP目录 
            ftpClient.changeWorkingDirectory(pathname); 
            ftpClient.setControlEncoding("GBK");
            FTPFile[] ftpFiles = ftpClient.listFiles(); 
            for(FTPFile file : ftpFiles){ 
                String ftpFilename = file.getName();
                ftpFilename = ftpFilename.substring(0, ftpFilename.lastIndexOf("."));
                if(filename.equalsIgnoreCase(ftpFilename)){
                    String fileName = new String(file.getName().getBytes("GBK"), "iso-8859-1");
                    ftpClient.dele(fileName);
                    flag = true; 
                    //删除文件成功后,判断目录下是否还有文件,没有则删除目录
                    deleteEmptyDir(pathname);
                    logger.info("删除文件成功");
                } 
            }
            ftpClient.logout();
        } catch (Exception e) { 
            logger.error("删除文件失败:" + e);
            throw new FrameExcelException(e);
        } finally {
            closeFtp();
        }
        return flag; 
    }
    
    /**
     * 删除空文件夹
     * @param pathname 文件路径
     * @throws IOException
     */
    public void deleteEmptyDir(String pathname) throws IOException {
        int fileNum = ftpClient.listFiles().length;
        if (fileNum == 0) {
            //切换到上一级目录对空文件夹进行删除
            ftpClient.changeWorkingDirectory("../");
            String dir = pathname.substring(pathname.lastIndexOf("/") + 1);
            //对删除的文件夹进行编码,防止中文名称文件夹无法删除的情况出现
            ftpClient.removeDirectory(new String(dir.getBytes("GBK"), "iso-8859-1"));
        }
    }
    
    /**
     * 关闭FTP服务器连接
     */
    public void closeFtp() {
        if(ftpClient.isConnected()){ 
            try{
                ftpClient.disconnect();
            }catch(IOException e){
                logger.error("关闭连接失败:" + e);
                throw new FrameExcelException(e);
            }
        } 
    }
    
    /**
     * 关闭流
     */
    public void closeStream(OutputStream out ,InputStream in) {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                logger.error("关闭连接异常:" + e);
                throw new FrameExcelException(e);
            }
        }
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                logger.error("关闭连接异常:" + e);
                throw new FrameExcelException(e);
            }
        }
    }
}
 

 

ftp.hostName=192.168.2.100
ftp.port=21
ftp.username=mes
ftp.password=xhmes

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值