FTP下载


package com.bfb.gateway.payment.service.utils;


import com.bfb.gateway.payment.entity.model.exception.PaymentException;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;


import java.io.*;
import java.net.SocketException;
import java.text.ParseException;


public class FtpUtils {
    private static final Logger logger = LoggerFactory.getLogger(FtpUtils.class);


    private FTPClient ftpClient;


    /**
     * init ftp servere
     */
    public FtpUtils(String ip, int port, String userName, String userPwd) {
        this.connectServer(ip, port, userName, userPwd);
    }
    public FtpUtils() {
    }
    /**
     * @param ip
     * @param port
     * @param userName
     * @param userPwd
     * @throws java.net.SocketException
     * @throws java.io.IOException 连接到服务器
     */
    public FTPClient connectServer(String ip, int port, String userName, String userPwd) {
        ftpClient = new FTPClient();
        try {
            // 连接
            ftpClient.connect(ip, port);


            // 登录
            if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                ftpClient.login(userName, userPwd);
            }else{
                ftpClient.disconnect();
            }
        } catch (SocketException e) {
            logger.error(e.getMessage());
        } catch (IOException e) {
            logger.error(e.getMessage());
        }
return ftpClient;
    }


    /**
     * @throws java.io.IOException 关闭连接
     */
    public void closeServer() {
        if (ftpClient.isConnected()) {
            try {
                ftpClient.logout();
                ftpClient.disconnect();
            } catch (IOException e) {
                logger.error(e.getMessage());
            }
        }
    }




    /**
     * 从FTP服务器上下载文件,支持断点续传
     * @param remotePath 远程文件路径
     * @param localPath 本地文件路径
     * @return 上传的状态
     * @throws java.io.IOException
     */
    public int downAllFiles(String remotePath, String localPath, String remoteEncoding, String fileEncoding) {
        logger.info("文件下载本地路径{},远程路径{},远程文件编码{},本地文件编码{}",localPath,remotePath,remoteEncoding,fileEncoding);
        try {
            // 设置被动模式
            ftpClient.enterLocalPassiveMode();


            // 设置以二进制方式传输
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);


            // 检查远程文件是否存在
            FTPFile[] files = ftpClient.listFiles(new String(remotePath.getBytes(fileEncoding), remoteEncoding));


            if (files.length < 1) {
                logger.error("远程文件不存在");
            }


            // 跳转到指定目录
            if (remotePath != null && remotePath.length() > 0) {
                ftpClient.changeWorkingDirectory(remotePath);
            }


            // 判断本地文件夹是否方存在
            File localDir = new File(localPath);
            if (!localDir.exists()) {
                localDir.mkdirs();
            }


            int count = 0;
            for (FTPFile ff : files) {
                long lRemoteSize = ff.getSize();
                String fildName = ff.getName();
                // 本地存在文件,进行断点下载
                File f = new File(localPath + File.separator + fildName);
                if (f.exists()) {
                    long localSize = f.length();
                    if (localSize >= lRemoteSize) {
                        logger.info("本地文件[{}]大于远程文件,下载中止", fildName);
                    }


                    // 进行断点续传,并记录状态
                    FileOutputStream out = new FileOutputStream(f, true);
                    ftpClient.setRestartOffset(localSize);
                    InputStream in = ftpClient.retrieveFileStream(new String(fildName.getBytes(fileEncoding), remoteEncoding));
                    byte[] bytes = new byte[1024];
                    int c;
                    while ((c = in.read(bytes)) != -1) {
                        out.write(bytes, 0, c);
                    }
                    in.close();
                    out.close();
                    boolean isDo = ftpClient.completePendingCommand();
                    if (isDo) {
                        logger.info("[{}]文件下载完毕", fildName);
                        count++;
                    } else {
                        logger.info("[{}]文件下载失败", fildName);
                    }
                } else {
                    OutputStream out = new FileOutputStream(f);
                    InputStream in = ftpClient.retrieveFileStream(new String(fildName.getBytes(fileEncoding), remoteEncoding));
                    byte[] bytes = new byte[1024];
                    int c;
                    while ((c = in.read(bytes)) != -1) {
                        out.write(bytes, 0, c);
                    }
                    in.close();
                    out.close();
                    boolean upNewStatus = ftpClient.completePendingCommand();
                    if (upNewStatus) {
                        logger.info("[{}]文件下载完毕", fildName);
                        count++;
                    } else {
                        logger.info("[{}]文件下载失败", fildName);
                    }
                }
            }
            return count;
        } catch (IOException e) {
            logger.error(e.getMessage());
            return 0;
        } finally {
            closeServer();
        }
    }


    /**
     * 从FTP服务器上下载文件,支持断点续传
     * @param remotePath 远程文件路径
     * @param localPath 本地文件路径
     * @return 上传的状态
     * @throws IOException
     */
    public int downFile(String remotePath, String localPath, String remoteEncoding, String fileEncoding,String fileName) throws PaymentException {
        logger.info("文件下载本地路径{},远程路径{},远程文件编码{},本地文件编码{},文件名称{}",localPath,remotePath,remoteEncoding,fileEncoding,fileName);
        try {
            // 设置被动模式
            ftpClient.enterLocalPassiveMode();


            // 设置以二进制方式传输
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);


            // 检查远程文件是否存在
            FTPFile[] files = ftpClient.listFiles(new String(remotePath.getBytes(fileEncoding), remoteEncoding));
            if (files.length < 1) {
                logger.error("远程文件不存在");
                throw new PaymentException(ConstantsPaymentRetCode.CHECK_FILE_ERROR_DOWNLOAD);
            }
            boolean flag=false;
            for (FTPFile ff : files){
                if(fileName.equals(ff.getName())){
                    flag=true;
                    break;
                }
            }
            if(!flag){
                logger.error("远程文件不存在");
                throw new PaymentException(ConstantsPaymentRetCode.CHECK_FILE_ERROR_DOWNLOAD);
            }




            // 跳转到指定目录
            if (remotePath != null && remotePath.length() > 0) {
                ftpClient.changeWorkingDirectory(remotePath);
            }


            // 判断本地文件夹是否方存在
            File localDir = new File(localPath);
            if (!localDir.exists()) {
                localDir.mkdirs();
            }


            int count = 0;
            // 本地存在文件,进行断点下载
            File f = new File(localPath + File.separator + fileName);
            if (f.exists()) {
                long localSize = f.length();


                // 进行断点续传,并记录状态
                FileOutputStream out = new FileOutputStream(f, true);
                ftpClient.setRestartOffset(localSize);
                InputStream in = ftpClient.retrieveFileStream(new String(fileName.getBytes(fileEncoding), remoteEncoding));
                byte[] bytes = new byte[1024];
                int c;
                while ((c = in.read(bytes)) != -1) {
                    out.write(bytes, 0, c);
                }
                in.close();
                out.close();
                boolean isDo = ftpClient.completePendingCommand();
                if (isDo) {
                    logger.info("[{}]文件下载完毕", fileName);
                    count++;
                } else {
                    logger.info("[{}]文件下载失败", fileName);
                }
            } else {
                OutputStream out = new FileOutputStream(f);
                InputStream in = ftpClient.retrieveFileStream(new String(fileName.getBytes(fileEncoding), remoteEncoding));
                byte[] bytes = new byte[1024];
                int c;
                while ((c = in.read(bytes)) != -1) {
                    out.write(bytes, 0, c);
                }
                in.close();
                out.close();
                boolean upNewStatus = ftpClient.completePendingCommand();
                if (upNewStatus) {
                    logger.info("[{}]文件下载完毕", fileName);
                    count++;
                } else {
                    logger.info("[{}]文件下载失败", fileName);
                }
            }
            return count;
        } catch (IOException e) {
            logger.error(e.getMessage());
            return 0;
        } finally {
            closeServer();
        }
    }


    /**
     * Description: 向FTP服务器上传文件
     * @param remotePath FTP服务器保存目录
     * @param filename 上传到FTP服务器上的文件名
     * @param f 输入流
     * @return 成功返回true,否则返回false
     */
    public  boolean uploadFile(String remotePath, String filename, File f) {
        boolean success = false;


        int reply = ftpClient.getReplyCode();
        try {
            ftpClient.enterLocalPassiveMode();
            ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.disconnect();
            }
            if (!ftpClient.changeWorkingDirectory(remotePath)) {// 如果不能进入dir下,说明此目录不存在!
                if (!ftpClient.makeDirectory(remotePath)) {
                    logger.info("创建文件目录【" + remotePath + "】 失败!");
                }
            }
            ftpClient.changeWorkingDirectory(remotePath);
            // 本地存在文件
            InputStream input = new FileInputStream(f);
            ftpClient.storeFile(filename, input);
            input.close();
            success = true;
        } catch (IOException e) {
            success =false ;
            logger.error(e.getMessage());
        } finally {
            closeServer();
        }
        return success;
    }


    /**
     * @param args
     * @throws java.text.ParseException
     */
    public static void main(String[] args) throws ParseException {
        //FtpUtils ftp = new FtpUtils("10.211.1.111", 21, "bangfubao-front1", "bangfubao");
        //int count = ftp.downAllFile("49261000","UTF-8","UTF-8","49261000");


        //int count = ftp.downAllFiles("49261000", "49261000", "UTF-8", "iso-8859-1");


        //System.out.println(count);
        //ftp.closeServer();
        //List<String> list = ftp.getFileList("49261000");
        //System.out.println(list.toString());
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
辉煌互联FTPserver这是一款免费的其特点是易于使用、绿色的(无需安装,只有一个文件)、小巧的的FTP服务器软件。整个FTP服务器就是一个EXE可执行程序,无需任何安装,不修改注册表,删除时直接删除所有相关文件就行了。程序放在任何目录均可运行。可以轻松地将它放在U盘里,邮箱里,网盘里,或者网站上随时下载,这样,就有了一个可以随身携带的FTP服务器软件。。这是一个小巧灵活的FTP服务器工具,占用系统资源少。可快速建立小型的FTP服务器,可以方便应用局域网内用户互相传送文件,不用再为如何另外安装FTP服务器上浪费脑筋。 功能说明: 1、建立便捷FTP服务器。 2、用于局域网,互相点对点传送文件。 3、建立临时FTP服务器,供大家临时下载文件等。 4、提供文件(文件夹)的下载、上传、删除、改名功能。 5、支持多用户访问,可以设置最大连接用户。 6、支持账户/密码访问和权限控制,同样支持匿名访问。 7、配置信息自动保存,下次不用重新输入,用户名清空自动恢复匿名访问。 8、最小化至托盘图标,不占用桌面空间。 9、能设置随系统开机启动。 程序设置: 启动软件后,需要作一些设置: 1. 设置FTP服务器的根目录。以后所有的请求都会以此FTP根目录为基础查找文件。 2. 设置FTP服务器的登录帐号,如果不设置即为允许匿名登录FTP服务器。 3. 设置FTP服务器端口,默认为 21
package com.kwantler.YN_EW.service.impl; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; public class FilePhoto { /** * 从网络Url中下载文件 * * @param urlStr * @param fileName * @param savePath * @throws IOException */ public static void downLoadByUrl(String urlStr, String fileName, String savePath) throws IOException { URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 设置超时间为3秒 conn.setConnectTimeout(5 * 1000); // 防止屏蔽程序抓取而返回403错误 conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); // 得到输入流 InputStream inputStream = conn.getInputStream(); // 获取自己数组 byte[] getData = readInputStream(inputStream); // 文件保存位置 File saveDir = new File(savePath); if (!saveDir.exists()) { saveDir.mkdir(); } File file = new File(saveDir + File.separator + fileName); FileOutputStream fos = new FileOutputStream(file); fos.write(getData); if (fos != null) { fos.close(); } if (inputStream != null) { inputStream.close(); } System.out.println("info:" + url + " download success"); } /** * 从输入流中获取字节数组 * * @param inputStream * @return * @throws IOException */ public static byte[] readInputStream(InputStream inputStream) throws IOException { byte[] buffer = new byte[1024]; int len = 0; ByteArrayOutputStream bos = new ByteArrayOutputStream(); while ((len = inputStream.read(buffer)) != -1) { bos.write(buffer, 0, len); } bos.close(); return bos.toByteArray(); } public static void main(String[] args) { try { downLoadByUrl( "https://www.mybiosource.com/images/tds/protocol_samples/MBS700_Antibody_Set_Sandwich_ELISA_Protocol.pdf", "ELISA.pdf", "E:/upload/protocol"); } catch (Exception e) { // TODO: handle exception } } }

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值