从ftp下载文件

来源:互联网 发布:java程序员培训课程 编辑:程序博客网 时间:2024/05/04 17:54
 /**     * @param filePath 远程文件路径     * @return     * @throws IOException     */    public static FTPFile[] getFileList(String url, String username, String password, String filePath) throws IOException {        FTPClient ftp = new FTPClient();        ftp.connect(url, 21);        //如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器        ftp.login(username, password);//登录        int reply = ftp.getReplyCode();        if (!FTPReply.isPositiveCompletion(reply)) {            ftp.disconnect();            return null;        }        FTPFile[] list = ftp.listFiles(filePath);        return list;    }    /**     * Description: 从FTP服务器下载文件     *     * @param url          FTP服务器hostname     * @param username     FTP登录账号     * @param password     FTP登录密码     * @param remotePath   FTP服务器上的相对路径     * @param localPath    下载后保存到本地的路径     * @param fileNameRule 文件名规则     * @return     */    public static boolean downFile(String url, String username, String password, String remotePath, String localPath, String Suffix, String fileNameRule) {        boolean success = false;        FTPClient ftp = new FTPClient();        try {            int reply;            ftp.connect(url, 21);            //如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器            ftp.login(username, password);//登录            reply = ftp.getReplyCode();            if (!FTPReply.isPositiveCompletion(reply)) {                ftp.disconnect();                return success;            }            //20140501目录            ftp.changeWorkingDirectory(remotePath);//转移到FTP服务器目录            FTPFile[] fs = ftp.listFiles();  //   20140501目录所有文件            for (FTPFile ff : fs) {                String ftpFileName = ff.getName();                String romoteFilePath = remotePath;                if (ftpFileName.endsWith(Suffix) && ftpFileName.contains(fileNameRule)) {                    logger.info("开始下载到:" + localPath + File.separatorChar + ftpFileName);                    File localFile = new File(localPath + File.separatorChar + ftpFileName);                    OutputStream is = new FileOutputStream(localFile);                    ftp.retrieveFile(romoteFilePath + "/" + ftpFileName, is);                    is.close();                    logger.info("下载完成:" + localPath + File.separatorChar + ftpFileName);                }            }            ftp.logout();            success = true;        } catch (IOException e) {            e.printStackTrace();        } finally {            if (ftp.isConnected()) {                try {                    ftp.disconnect();                } catch (IOException ioe) {                }            }        }        return success;    }

0 0
原创粉丝点击