java中操作FTP

package com.neusoft.syqxj.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.SocketException;

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 org.apache.log4j.Logger;

public class FtpUtil {
    /**日志*/
    //private static final Logger logger=Logger.getLogger(FtpUtil.class.getName());

    /** 创建FTP连接 */
    public static FTPClient getClient(String ip, int port, String name, String pwd) {
        FTPClient ftp = null;
        try {
            ftp = new FTPClient();
            int reply;
            ftp.connect(ip, port);
            ftp.setControlEncoding("GBK");
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                ftp = null;
            }
            if (!ftp.login(name, pwd)) {
                ftp.logout();
                ftp = null;
            }
        } catch (SocketException e) {
            e.printStackTrace();
            //logger.error(e.toString()+"@line:"+e.getStackTrace()[0].getLineNumber());
        } catch (IOException e) {
            e.printStackTrace();
            //logger.error(e.toString()+"@line:"+e.getStackTrace()[0].getLineNumber());
        }
        return ftp;
    }

    /** 文件下载 从客服FTP下载到本地 */
    public static String download(FtpBean ftp) throws IOException {
        String fileData = "";
        String filename = ftp.getFileName();
        String remotePath = "";
        boolean exist = false;
        OutputStream os = null;
        InputStream is = null;
        File localFile =null;
        FTPClient otherClient = null;
        try {
            otherClient = FtpUtil.getClient(ftp.getIp(), ftp.getPort(), ftp.getUsername(), ftp.getPassword());
            otherClient.setFileType(FTP.BINARY_FILE_TYPE);
            String fpath= new String(ftp.getFtpPath().getBytes("gbk"), "iso-8859-1");
            FTPFile[] files = otherClient.listFiles(fpath);
            FTPFile file = new FTPFile();
            for (int j = 0; j < files.length; j++) {
                file = files[j];
                if (file.getName().contains(filename)) {
              //      logger.info("【查找到目标文件:"+ files[j]+" 】");
                    exist = true;
                    remotePath = ftp.getFtpPath() + filename;
                    is = otherClient.retrieveFileStream(new String(remotePath.getBytes("gbk"), "iso-8859-1"));// 获取文件流
                    if (is != null) {
                        String filePath=ftp.getLocalPath()+"/"+ filename;
                //        logger.info("【filePath:"+filePath+"】");
                        localFile = new File(filePath);
                        os = new FileOutputStream(localFile);
                        int bytesRead = 0;
                        byte[] buffer = new byte[5 * 1024];
                        while ((bytesRead = is.read(buffer)) != -1) {
                            os.write(buffer, 0, bytesRead);//将文件发送到客户端
                        }
                        BufferedReader in = new BufferedReader(new FileReader(localFile));
                        StringBuffer sb = new StringBuffer();
                        String str;
                        while ((str = in.readLine()) != null) {
                            sb.append(str);
                        }
                        in.close();
                        fileData = sb.toString();
             //           logger.info("【 "+filename+" 文件下载成功】");
                        break;
                    } else {
               //         logger.info("【文件内容为空,请联系管理员】");
                    }
                }
            }
            if (!exist) {
               // logger.info("【目标文件不存在】");
            } else {
                //logger.info("【文件内容:"+fileData+" 】");
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            //logger.error(e.toString()+"@line:"+e.getStackTrace()[0].getLineNumber());
        } catch (IOException e) {
            e.printStackTrace();
            //logger.error(e.toString()+"@line:"+e.getStackTrace()[0].getLineNumber());
        } catch (Exception e) {
            e.printStackTrace();
            //logger.error(e.toString()+"@line:"+e.getStackTrace()[0].getLineNumber());
        } finally {
            if (os != null) {
                os.close();
            }
//            if(exist){
//                otherClient.deleteFile(new String(remotePath.getBytes("UTF-8"), "iso-8859-1"));//删除远程文件
//                boolean mark=deleteFile(localFile);//删除本地文件
//                if(mark){
//                    logger.info("【删除文件成功】");
//                }
//            }
            otherClient.disconnect();
        }
        return fileData;
    }

    /** FTP上传封装 */
    public static boolean upLoad(FtpBean bean, String fileName) {
        try {
            FTPClient ftp = null;
            ftp = FtpUtil.getClient(bean.getIp(), bean.getPort(), bean.getUsername(), bean.getPassword());
            if (ftp != null) {
                ftp.setFileType(FTP.BINARY_FILE_TYPE);
                ftp.enterLocalPassiveMode();
                ftp.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
                InputStream input = new FileInputStream(fileName);
                String filename = new String(bean.getFileName().getBytes("gbk"), "iso-8859-1");
                String fpath= new String(bean.getFtpPath().getBytes("gbk"), "iso-8859-1");
                ftp.storeFile(fpath + filename, input); // 保存到ftp
                //logger.info("文件上传成功: " + bean.getFtpPath() + filename);
                input.close();
                ftp.logout();
            } else {
                //logger.info("FTP连接异常:com.ipi.common.upLoad:69");
                return false;
            }
        } catch (SocketException e) {
            e.printStackTrace();
            //logger.error(e.toString()+"@line:"+e.getStackTrace()[0].getLineNumber());
            return false;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            //logger.error(e.toString()+"@line:"+e.getStackTrace()[0].getLineNumber());
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            //logger.error(e.toString()+"@line:"+e.getStackTrace()[0].getLineNumber());
            return false;
        }

        return true;
    }

    /**
     * 删除单个文件
     * @param   sPath    被删除文件的文件名
     * @return 单个文件删除成功返回true,否则返回false
     */
    public boolean deleteFile(File file) {
        boolean flag = false;
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }
        return flag;
    }
    public static void main(String[] args){
        FtpBean bean=new FtpBean();
        bean.setIp("10.86.83.113");
        bean.setPort(21);
        bean.setUsername("admin");
        bean.setPassword("1");
        bean.setFtpPath("/测试/");
        bean.setFileName("新建.txt");
        //String fileName="c:\\新建.txt";
       // FtpUtil.upLoad(bean, fileName);
        bean.setLocalPath("d:");
        try {
            FtpUtil.download(bean);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 创建 Ftp实体类
public class FtpBean {

    private String ip; // Ftp服务器的IP地址

    private int port; // FtP端口号

    private String username; // Ftp服务器登录名

    private String password; // Ftp服务器登录密码

    private String ftpPath; // FTP文件放置路径

    private String localPath; // 文件本地路径

    private String loadPath; // 下载文件放置路径

    private String fileName; // 文件名称

    public String getIp() {
        return ip;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值