FTP下载文件

//需要注意的是下载文件时的编码格式需要和FTP服务器的编码格式保持一致。搜索代码中的 this.ftpClient.setControlEncoding("GBK");package net.ssd.publish.web.filter;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.TimeZone;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;

import sun.net.ftp.FtpClient;

/**
 * @ClassName FtpClient
 * @Description TODO: add type description
 * @author wangzm
 * @2013-12-12下午2:28:39
 */
public class FtpClient1 {
    private FTPClient ftpClient;
    private String strIp;
    private int intPort;
    private String user;
    private String password;

    private static Logger logger = Logger.getLogger(FtpClient1.class.getName());

    /* *
     * Ftp构造函数
     */
    public FtpClient1(String strIp, int intPort, String user, String Password) {
        this.strIp = strIp;
        this.intPort = intPort;
        this.user = user;
        this.password = Password;
        this.ftpClient = new FTPClient();
    }

    /**
     * @return 判断是否登入成功
     * */
    public boolean connect() {
        if (this.ftpClient.isConnected())
            return true;
        boolean isLogin = false;
        FTPClientConfig ftpClientConfig = new FTPClientConfig();
        ftpClientConfig.setServerTimeZoneId(TimeZone.getDefault().getID());
//        this.ftpClient.setControlEncoding("GBK");
        this.ftpClient.setControlEncoding("UTF-8");
        this.ftpClient.configure(ftpClientConfig);
        try {
            if (this.intPort > 0) {
                this.ftpClient.connect(this.strIp, this.intPort);
            } else {
                this.ftpClient.connect(this.strIp);
            }
            // FTP服务器连接回答
            int reply = this.ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                this.ftpClient.disconnect();
                logger.error("登录FTP服务失败!");
                return isLogin;
            }
            isLogin = this.ftpClient.login(this.user, this.password);
            if(isLogin){
                // 设置传输协议
                this.ftpClient.enterLocalPassiveMode();
                this.ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
                logger.info("恭喜" + this.user + "成功登陆FTP服务器");
            }else{
                throw new RuntimeException("服务器拒绝了连接");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(this.user + "登录FTP服务失败!" + e.getMessage());
        }
        this.ftpClient.setBufferSize(1024 * 2);
        this.ftpClient.setDataTimeout(30 * 1000);
        return isLogin;
    }

    /**
     * @退出关闭服务器链接
     * */
    public void disconnect() {
        if (null != this.ftpClient && this.ftpClient.isConnected()) {
            try {
                boolean reuslt = this.ftpClient.logout();// 退出FTP服务器
                if (reuslt) {
                    logger.info("成功退出服务器");
                }
            } catch (IOException e) {
                e.printStackTrace();
                logger.warn("退出FTP服务器异常!" + e.getMessage());
            } finally {
                try {
                    this.ftpClient.disconnect();// 关闭FTP服务器的连接
                } catch (IOException e) {
                    e.printStackTrace();
                    logger.warn("关闭FTP服务器的连接异常!");
                }
            }
        }
    }

    /***
     * 上传Ftp文件
     *
     * @param localFile
     *            当地文件
     * @param romotUpLoadePath上传服务器路径
     *            - 应该以/结束
     * */
    public boolean uploadFile(File localFile, String romotUpLoadePath) {
        return this.uploadFile(localFile, romotUpLoadePath, null);
    }

    /**
     * 上传Ftp文件
     *
     * @param localFile
     *            本地文件
     * @param romoteFileName
     *            上传到FTP后的文件名称
     * @param romotUpLoadePath
     *            上传到FTP的目录,如果为空就是当前目录
     * @return
     */
    public boolean uploadFile(File localFile, String romotUpLoadePath, String romoteFileName) {
        BufferedInputStream inStream = null;
        boolean success = false;
        try {
            if (romotUpLoadePath != null) {
                boolean flag = this.ftpClient.changeWorkingDirectory(romotUpLoadePath);// 改变工作路径
                if (!flag) {
                    this.ftpClient.makeDirectory(romotUpLoadePath);
                    this.ftpClient.changeWorkingDirectory(romotUpLoadePath);
                }
            }

            inStream = new BufferedInputStream(new FileInputStream(localFile));
            logger.info(localFile.getName() + "开始上传.....");
            if (romoteFileName == null)
                romoteFileName = localFile.getName();
            success = this.ftpClient.storeFile(romoteFileName, inStream);
            if (success == true) {
                logger.info(localFile.getName() + "上传成功");
                return success;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            logger.error(localFile + "未找到");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inStream != null) {
                try {
                    inStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return success;
    }

    /***
     * 下载文件
     *
     * @param remoteFileName
     *            待下载文件名称
     * @param localDires
     *            下载到当地那个路径下
     * @param remoteDownLoadPath
     *            remoteFileName所在的路径
     * */

    public boolean downloadFile(String remoteFileName, String localDires, String remoteDownLoadPath) {
        String strFilePath = localDires + remoteFileName;
        BufferedOutputStream outStream = null;
        boolean success = false;
        try {
            this.ftpClient.changeWorkingDirectory(remoteDownLoadPath);

            File f = new File(strFilePath);
            if(!f.getParentFile().exists())
                f.getParentFile().mkdirs();
            outStream = new BufferedOutputStream(new FileOutputStream(f));
            logger.info(remoteFileName + "开始下载....");
            success = this.ftpClient.retrieveFile(remoteFileName, outStream);
            if (success == true) {
                logger.info(remoteFileName + "成功下载到" + strFilePath);
                return success;
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(remoteFileName + "下载失败");
        } finally {
            if (null != outStream) {
                try {
                    outStream.flush();
                    outStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        if (success == false) {
            logger.error(remoteFileName + "下载失败!!!");
        }
        return success;
    }

    /***
     * @上传文件夹
     * @param localDirectory
     *            当地文件夹
     * @param remoteDirectoryPath
     *            Ftp 服务器路径 以目录"/"结束
     * */
    public boolean uploadDirectory(String localDirectory, String remoteDirectoryPath) {
        File src = new File(localDirectory);
        try {
            remoteDirectoryPath = remoteDirectoryPath + src.getName() + "/";
            this.ftpClient.makeDirectory(remoteDirectoryPath);
            // ftpClient.listDirectories();
        } catch (IOException e) {
            e.printStackTrace();
            logger.info(remoteDirectoryPath + "目录创建失败");
        }
        File[] allFile = src.listFiles();
        if (allFile != null) {
            for (int currentFile = 0; currentFile < allFile.length; currentFile++) {
                if (!allFile[currentFile].isDirectory()) {
                    String srcName = allFile[currentFile].getPath().toString();
                    uploadFile(new File(srcName), remoteDirectoryPath);
                }
            }
            for (int currentFile = 0; currentFile < allFile.length; currentFile++) {
                if (allFile[currentFile].isDirectory()) {
                    // 递归
                    uploadDirectory(allFile[currentFile].getPath().toString(), remoteDirectoryPath);
                }
            }
        }
        return true;
    }

    /***
     * 下载文件夹
     * @param localDirectoryPath本地地址
     * @param remoteDirectory
     *            远程文件夹
     * */
    public boolean downLoadDirectory(String localDirectoryPath, String remoteDirectory) {
        try {
            String fileName = new File(remoteDirectory).getName();
            localDirectoryPath = localDirectoryPath + fileName + "//";
            new File(localDirectoryPath).mkdirs();
            FTPFile[] allFile = this.ftpClient.listFiles(remoteDirectory);
            if (allFile != null) {
                for (int currentFile = 0; currentFile < allFile.length; currentFile++) {
                    if (!allFile[currentFile].isDirectory()) {
                        downloadFile(allFile[currentFile].getName(), localDirectoryPath, remoteDirectory);
                    }
                }
                for (int currentFile = 0; currentFile < allFile.length; currentFile++) {
                    if (allFile[currentFile].isDirectory()) {
                        String strremoteDirectoryPath = remoteDirectory + "/" + allFile[currentFile].getName();
                        downLoadDirectory(localDirectoryPath, strremoteDirectoryPath);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            logger.info("下载文件夹失败");
            return false;
        }
        return true;
    }

    /**
     * 重命名远程文件
     * @param name  要改名的原始文件名
     * @param newName  新的文件名
     * @return
     * @author wangzm
     */
    public boolean rename(String name, String newName){
        boolean r = false;
        try {
            r = this.ftpClient.rename(name, newName);
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("将“"+name+"”重命名为“"+newName+"”失败");
        }
        return r;
    }

    // FtpClient的Set 和 Get 函数
    public FTPClient getFtpClient() {
        return ftpClient;
    }

    @Deprecated
    public void setFtpClient(FTPClient ftpClient) {
        this.ftpClient = ftpClient;
    }

    public static void main(String[] args) throws IOException {
        /*FtpClient ftp = new FtpClient("127.0.0.1", 21, "ftp1", "123");
        ftp.connect();
        // 上传文件夹
        // ftp.uploadDirectory("D:/大连-发布大风黄色20130923171253.doc", "/2013");
        ftp.uploadFile(new File("D:/大连-发布大风黄色20130923171253.doc"), "/2013/");
        // 下载文件夹
        // ftp.downLoadDirectory("d://tmp//", "/home/data/DataProtemp");
        ftp.disconnect();*/

        FtpClient1 t = new FtpClient1("192.168.0.27", 21, "ssdsms", "ssdsms");
        t.connect();
        t.downloadFile("云南一键发.txt","D:/",  "/");
        t.disconnect();
//        String s ="asdf{^}sa";
//        String[] ss = s.split("\\{\\^\\}");
//        logger.info(ss[1]);
    }
}
时间: 2024-11-04 03:10:12

FTP下载文件的相关文章

FTP下载文件工具类

FTP文件下载需要的jar包commons-net-2.0.jar有时还需要:jakarta-oro.jar 1 package com.wdxc.util; 2 3 import java.io.File; 4 import java.io.FileOutputStream; 5 import java.io.IOException; 6 import java.io.OutputStream; 7 import java.util.HashMap; 8 import java.util.Ma

Python之ftp下载文件测试代码

IT审计中有一个最多的执行步骤就是取证.最近的项目过程中,有需要验证ftp服务机密性的需要,就写了一个ftp访问并下载文件的脚本. 此步骤实现目的有三: 1.ftp是否可以匿名访问到敏感信息. 2.在渗透人员拥有低等.中等技术水平前提下,目标ftp服务器的日志记录.入侵检测等是否会产生记录.阻断及预警功能. 3.也是最重要的,在上述条件下,此举基于可渗透时间.现行部署条件.应对防御未来直接支出代价.数据丢失严重性综合得出判断结论,并据此给出建议. 1 #coding=utf-8 2 import

c#.net从ftp下载文件到本地

c#.net从ftp下载文件到本地    /*首先从配置文件读取ftp的登录信息*/ string TempFolderPath = System.Configuration.ConfigurationManager.AppSettings["TempFolderPath"].ToString(); string FtpUserName = System.Configuration.ConfigurationManager.AppSettings["FtpUserName&q

AIX 用SHELL脚本 自动FTP下载文件

用SHELL脚本 自动FTP下载文件:kaiboss1:/weblogic/bboss> uname -xAIX kaiboss1 3315381580 3 5 00C59CB54C00kaiboss1:/weblogic/bboss> more ./memberupload/memberupload.shcd /weblogic/bboss/memberupload/fileftp -inv 10.1.140.123 <<!>memberfile.loguser ftp31

C#FTP下载文件出现远程服务器返回错误: (500) 语法错误,无法识别命令

如果下载多个文件的时候,有时候莫名其妙的出现500服务器错误,很有可能是没有设置KeepAlive 属性导致的. 出现应用程序未处理的异常:2015/1/6 11:40:56 异常类型:WebException 异常消息:远程服务器返回错误: (500) 语法错误,无法识别命令. 参考:http://www.cnblogs.com/webabcd/archive/2007/01/21/626242.html KeepAlive - 指定连接是应该关闭还是在请求完成之后关闭,默认为true ///

.Net 连接FTP下载文件报错:System.InvalidOperationException: The requested FTP command is not supported when using HTTP proxy

系统环境: Windows + .Net Framework 4.0 问题描述: C#连接FTP下载文件时,在部分电脑上有异常报错,在一部分电脑上是正常的:异常报错的信息:System.InvalidOperationException: The requested FTP command is not supported when using HTTP proxy 分析过程: 在网上搜索到的解决方案,基本都是将代理置为null:request.Proxy = null; 并没有解释其原因. 调

Qt利用FTP下载文件

自己封装的ftpCtrl类,测试正常下载文件. 原文:默默地EEerhttp://www.cnblogs.com/hebaichuanyeah/p/6083036.html ftpCtrl.h #ifndef FTPCTRL_H #define FTPCTRL_H #include <QFile> #include <QFtp> class FtpCtrl : public QObject { Q_OBJECT public: FtpCtrl(QObject *parent = 0

java实现FTP下载文件

ftp上传下载文件,是遵照ftp协议上传下载文件的,本例仅以下载文件为例. 重要的方法解释: 1.FTP功能相关依赖路径:org.apache.commons.net.ftp.*: 2.ftp默认端口是21,如果非默认端口连接,需指定:ftp.connect(ftphostaddr, 22);//22为端口号 3.ftp.changeWorkingDirectory(ftppath) //实现切换目录 4.FTPFile[] fs = ftp.listFiles(); 获取指定目录下的文件列表

【197】PowerShell 通过 FTP 下载文件

参考:使用 WGET 从FTP上下载文件 在 PowerShell 使用 wget2 工具,代码如下: wget2 ftp://user:[email protected]/1.jpg 其中 user 替换为远程 ftp 的用户名password 替换为远程 ftp 的密码

(转)FTP操作类,从FTP下载文件

using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Net; using System.Windows.Forms; namespace PCMDataImporter { /// <summary> /// 封装了FTP的两个操作:下载文件Download()和获取FTP服务器上文件列表信息GetFileList() /// </summary&