FtpUtils文件操作工具类

该代码片段展示了如何在Java中使用ApacheCommonsNet库进行FTP操作,包括登录FTP服务器、上传文件、下载文件、删除文件、预览文件以及处理文件重命名等。主要类FtpApche包含了这些功能的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

导入ftp依赖

<!-- ftp -->
    <dependency>
	    <groupId>commons-net</groupId>
	    <artifactId>commons-net</artifactId>
	    <version>3.6</version>
	</dependency>

FtpUtils

package com.onlineboot.utils;

import cn.hutool.core.util.StrUtil;
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 javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.UUID;

/**
 * @Author: wangyu
 * @Date: 2020/12/25 10:28
 */
public class FtpApche {

    private static FTPClient ftpClient = new FTPClient();
    private static String encoding = "GBK";
    private static final Logger logger = LoggerFactory.getLogger(FtpApche.class);
    private static String tempPath = "/temp";
    /*
    * 登录FTP
    * */
    public static boolean ftpLogin(String url, int port, String username, String password){
        boolean result = false;

        int reply;
        try {
            ftpClient.connect(url,port);
            ftpClient.login(username,password);
            ftpClient.setControlEncoding(encoding);

            //检查是否连接成功
            reply = ftpClient.getReplyCode();
            if(!FTPReply.isPositiveCompletion(reply)){
                logger.info("FTP连接失败");
                ftpClient.disconnect();
                return result;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return true;
    }

    /*
    * Description:向FTP服务器上传文件
    *
    * @param url FTP 服务器hostname
    * @param port FTP服务器端口
    * @param username FTP登录密码
    * @param path FTP服务器保存目录,如果是根目录则为“/”
    * @param filename 上传到FTP服务器上的文件名
    * @param input 本地文件输入流
    * @return 成功返回true, 否则返回false
    * */
    public static boolean testUploadFile(String url, int port, String username, String password, String path, String filename,InputStream input){
        boolean result = false;

        int reply;

        try {
            ftpClient.connect(url,port);

            ftpClient.login(username,password);
            ftpClient.setControlEncoding(encoding);

            //检查是否连接成功
            reply = ftpClient.getReplyCode();
            if(!FTPReply.isPositiveCompletion(reply)){
                System.out.println("连接失败");
                ftpClient.disconnect();
                return result;
            }

            //转移工作目录至指定目录下
            boolean change = ftpClient.changeWorkingDirectory(path);
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            if(change){
                ftpClient.setBufferSize(1024*1024);
                BufferedInputStream in = new BufferedInputStream(input);
                result = ftpClient.storeFile(new String(filename.getBytes(encoding),"iso-8859-1"),in);
                if(result){
                    System.out.println("上传成功");
                }
                in.close();
            }
            input.close();
            ftpClient.logout();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (ftpClient.isConnected()){
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                ;
            }
        }
        return result;
    }

    /*
    * Description: 从FTP服务器下载文件
    *
    * @Version1.0
    * @param url FTP服务器hostname
    * @param port FTP服务器端口
    * @param username FTP登录密码
    * @param remotePath FTP服务器上的相对路径
    * @param fileName 要下载的文件名
    *
    * */
    public static boolean downFile(String url, int port, String username, String password, String remotePath, String fileName,String nowFileName, HttpServletResponse response){
        boolean result = false;

        try {
            int reply;
            ftpClient.setControlEncoding(encoding);

            ftpClient.connect(url,port);
            ftpClient.login(username,password);

            reply = ftpClient.getReplyCode();
            if(!FTPReply.isPositiveCompletion(reply)){
                ftpClient.disconnect();
                System.err.println("FTP server refused connection");
                return result;
            }

            //设置文件传输类型为二进制
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            //转移到FTP服务器目录至指定的目录下
            ftpClient.changeWorkingDirectory(remotePath);

            //获取文件列表
            FTPFile[] fs = ftpClient.listFiles();
            for (FTPFile ff : fs){
                if(ff.getName().equals(fileName)){
                    //设置响应头,控制浏览器下载该文件
                    response.reset();
                    response.setContentType("application/vnd.ms-excel;charset=utf-8");
                    response.setHeader("Content-disposition", "attachment;filename="+new String(nowFileName.getBytes("GB2312"),"ISO8859_1"));
                    response.setCharacterEncoding(encoding);
                    ftpClient.setBufferSize(1024*1024);
                    BufferedInputStream bis = new BufferedInputStream(ftpClient.retrieveFileStream(ff.getName()));
                    BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
                    byte buffer[] = new byte[4096];
                    int len;
                    while((len = bis.read(buffer)) > 0){
                        bos.write(buffer, 0, len);
                    }
                    bis.close();
                    bos.close();
                }
            }

            ftpClient.logout();
            result = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(ftpClient.isConnected()){
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    /*
     * Description: 从FTP服务器下载文件
     *
     * @Version1.0
     * @param url FTP服务器hostname
     * @param port FTP服务器端口
     * @param username FTP登录密码
     * @param remotePath FTP服务器上的相对路径
     * @param fileName 要下载的文件名
     *
     * */
    public static boolean downFzFile(String url, int port, String username, String password, String remotePath, String fileName,String nowFileName, HttpServletResponse response){
        boolean result = false;
        BufferedInputStream bis = null ;
        BufferedOutputStream bos = null ;
        try {
            int reply;
            ftpClient.setControlEncoding(encoding);

            ftpClient.connect(url,port);
            ftpClient.login(username,password);

            reply = ftpClient.getReplyCode();
            if(!FTPReply.isPositiveCompletion(reply)){
                ftpClient.disconnect();
                System.err.println("FTP server refused connection");
                return result;
            }

            //设置文件传输类型为二进制
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            //转移到FTP服务器目录至指定的目录下
            ftpClient.changeWorkingDirectory(remotePath);

            //获取文件列表
            FTPFile[] fs = ftpClient.listFiles();
            for (FTPFile ff : fs){
                if(ff.getName().equals(fileName)){
                    bis = new BufferedInputStream(ftpClient.retrieveFileStream(ff.getName()));
                    //设置响应头,控制浏览器下载该文件
                    response.setContentType("application/x-dowmload");
                    response.setContentType("application/octet-stream");
                    response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(nowFileName,"UTF-8"));
                    response.addHeader("Content-Length","" + ff.getSize());
                    ftpClient.setBufferSize(1024*1024);
                    System.out.println("----------------------------------634650-------"+ff.getSize());
                    bos = new BufferedOutputStream(response.getOutputStream());
                    byte buffer[] = new byte[102400];
                    int len = -1;
                    while((len = bis.read(buffer)) != -1){
                        bos.write(buffer, 0, len);
                    }
                    bis.close();
                    bos.flush();
                    bos.close();
                }
            }
            ftpClient.logout();
            result = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(ftpClient.isConnected()){
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    /*
     * Description: 删除FTP服务器上的文件
     *
     * @Version1.0
     * @param url FTP服务器hostname
     * @param port FTP服务器端口
     * @param username FTP登录密码
     * @param remotePath FTP服务器上的相对路径
     * @param fileName 要下载的文件名
     *
     * */
    public static boolean deleteFtpFile(String url,int port,String username,String password,String remotePath,String fileName){
        boolean flag = false;
        int reply;


        try {
            ftpClient.connect(url,port);
            ftpClient.login(username,password);
            ftpClient.setControlEncoding(encoding);
            //检查是否连接成功
            reply = ftpClient.getReplyCode();
            if(!FTPReply.isPositiveCompletion(reply)){
                logger.info("连接失败");
                ftpClient.disconnect();
                return flag;
            }

            //转移工作目录至指定目录下
            boolean change = ftpClient.changeWorkingDirectory(remotePath);
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            if(change){
                ftpClient.dele(fileName);
                ftpClient.logout();
                flag = true;
            }
            logger.info("文件删除成功");
        } catch (IOException e) {
            logger.info("文件删除失败");
            e.printStackTrace();
        }finally {
            if (ftpClient.isConnected()){
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return flag;
    }


    /*
     * Description: 从FTP服务器下载文件进行预览
     *
     * @Version1.0
     * @param url FTP服务器hostname
     * @param port FTP服务器端口
     * @param username FTP登录密码
     * @param remotePath FTP服务器上的相对路径
     * @param fileName 要下载的文件名
     *
     * */
    public static InputStream lookFile(String url,int port,String username,String password,String remotePath,String fileName){

        try {
            int reply;
            ftpClient.setControlEncoding(encoding);

            ftpClient.connect(url,port);
            ftpClient.login(username,password);

            reply = ftpClient.getReplyCode();
            if(!FTPReply.isPositiveCompletion(reply)){
                ftpClient.disconnect();
                logger.info("FTP server refused connection");
                return null;
            }

            //设置文件传输类型为二进制
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            //转移到FTP服务器目录至指定的目录下
            ftpClient.changeWorkingDirectory(remotePath);

            //获取文件列表
            FTPFile[] fs = ftpClient.listFiles();
            for (FTPFile ff : fs){
                if(ff.getName().equals(fileName)){
                    ftpClient.setControlEncoding("UTF-8");
                    return ftpClient.retrieveFileStream(ff.getName());
                }
            }

            ftpClient.logout();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(ftpClient.isConnected()){
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /*
     * Description: 从FTP服务器下载pdf预览
     *
     * @Version1.0
     * @param url FTP服务器hostname
     * @param port FTP服务器端口
     * @param username FTP登录密码
     * @param remotePath FTP服务器上的相对路径
     * @param fileName 要下载的文件名
     *
     * */
    public static boolean lookPdf(String url, int port, String username, String password, String remotePath, String fileName,HttpServletResponse response){
        boolean result = false;
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "inline;filename="+fileName);
        try {
            int reply;
            ftpClient.setControlEncoding(encoding);

            ftpClient.connect(url,port);
            ftpClient.login(username,password);

            reply = ftpClient.getReplyCode();
            if(!FTPReply.isPositiveCompletion(reply)){
                ftpClient.disconnect();
                logger.info("FTP server refused connection");
                return result;
            }

            //设置文件传输类型为二进制
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            //转移到FTP服务器目录至指定的目录下
            ftpClient.changeWorkingDirectory(remotePath);

            //获取文件列表
            FTPFile[] fs = ftpClient.listFiles();
            for (FTPFile ff : fs){
                if(ff.getName().equals(fileName)){
                    ftpClient.setBufferSize(1024*1024);
                    BufferedInputStream bis = new BufferedInputStream(ftpClient.retrieveFileStream(ff.getName()));
                    BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
                    byte buffer[] = new byte[4096];
                    int len;
                    while((len = bis.read(buffer)) > 0){
                        bos.write(buffer, 0, len);
                    }
                    bis.close();
                    bos.close();
                }
            }

            ftpClient.logout();
            response.getOutputStream().flush();
            result = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(ftpClient.isConnected()){
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }


    /*
     * Description: 从FTP服务器下载图片进行预览
     *
     * @Version1.0
     * @param url FTP服务器hostname
     * @param port FTP服务器端口
     * @param username FTP登录密码
     * @param remotePath FTP服务器上的相对路径
     * @param fileName 要下载的文件名
     *
     * */
    public static String lookPicture(String url,int port,String username,String password,String remotePath,String fileName){
        InputStream inputStream = null;
        String re = null;

        try {
            int reply;
            ftpClient.setControlEncoding(encoding);

            ftpClient.connect(url,port);
            ftpClient.login(username,password);

            reply = ftpClient.getReplyCode();
            if(!FTPReply.isPositiveCompletion(reply)){
                ftpClient.disconnect();
                logger.info("FTP server refused connection");
                return null;
            }

            //设置文件传输类型为二进制
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            //转移到FTP服务器目录至指定的目录下
            ftpClient.changeWorkingDirectory(remotePath);

            //获取文件列表
            FTPFile[] fs = ftpClient.listFiles();
            for (FTPFile ff : fs){
                //解决中文乱码问题,两次解决
                //byte[] bytes = ff.getName().getBytes("iso-8859-1");
                //String ftpFileName = new String(bytes,"utf-8");
                if(fileName.equals(ff.getName())){
                    inputStream = ftpClient.retrieveFileStream(ff.getName());
                }
            }

            if (inputStream != null){
                try {
                    byte[] data;
                    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                    int dataSize = 0;
                    while (dataSize == 0){
                        dataSize = inputStream.available();//avalilable()方法为非阻塞式方法,但read()为阻塞式方法,即还没有将文件写完就读文件大小是读不到的
                    }
                    data = new byte[inputStream.available()];
                    int len = 0;
                    while ((len = inputStream.read(data)) != -1){
                        outputStream.write(data,0,len);
                    }
                    data = outputStream.toByteArray();
                    Base64.Encoder encoder = Base64.getEncoder();
                    re = encoder.encodeToString(data);
                    inputStream.close();//转换完成,关闭流
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

           ftpClient.logout();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(ftpClient.isConnected()){
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(null != inputStream){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return re;
    }

    /*
     * Description:向FTP服务器上传文件
     *
     * @param url FTP 服务器hostname
     * @param port FTP服务器端口
     * @param username FTP登录密码
     * @param path FTP服务器保存目录,如果是根目录则为“/”
     * @param filename 上传到FTP服务器上的文件名
     * @param input 本地文件输入流
     * @return 成功返回true, 否则返回false
     * */
    public static boolean uploadFile(String url, int port, String username, String password, String path, String filename,InputStream input){
        boolean result = false;
        int reply;

        try {
            ftpClient.connect(url,port);
            ftpClient.login(username,password);
            ftpClient.setControlEncoding(encoding);

            //检查是否连接成功
            reply = ftpClient.getReplyCode();
            if(!FTPReply.isPositiveCompletion(reply)){
                logger.info("连接失败");
                ftpClient.disconnect();
                return result;
            }

            //转移工作目录至指定目录下
            boolean change = ftpClient.changeWorkingDirectory(path);
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            if(!change){
                String[] split = path.split("/");
                String tempPath = "";
                for (String str: split) {
                    if(StrUtil.isEmpty(str)){
                        continue;
                    }
                    tempPath+="/"+str;
                    if(!ftpClient.changeWorkingDirectory(tempPath)){
                        if(!ftpClient.makeDirectory(tempPath)){
                            return result;
                        }else {
                         change =  ftpClient.changeWorkingDirectory(tempPath);
                        }
                    }
                }
            }
            if(change){
                ftpClient.setBufferSize(1024*1024);
                BufferedInputStream in = new BufferedInputStream(input);
                result = ftpClient.storeFile(new String(filename.getBytes(encoding),"iso-8859-1"),in);
                if(result){
                    logger.info("上传成功");
                }
                in.close();
            }
            input.close();
            ftpClient.logout();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (ftpClient.isConnected()){
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    /*
     * Description:获取ftp指定目录下的文件夹名称
     *
     * @param url FTP 服务器hostname
     * @param port FTP服务器端口
     * @param username FTP登录密码
     * @param password FTP登录密码
     * @param path FTP服务器保存目录,如果是根目录则为“/”
     * @return 文件夹名称集合
     * */
    public static List<String> getFileDirectoryList(String url, Integer port, String username, String password, String path) {
        List<String> resultList = new ArrayList<>();
        int reply;
        try{
            ftpClient.connect(url,port);

            ftpClient.login(username,password);
            ftpClient.setControlEncoding(encoding);

            //检查是否连接成功
            reply = ftpClient.getReplyCode();
            if(!FTPReply.isPositiveCompletion(reply)){
                logger.info("连接失败");
                ftpClient.disconnect();
                return resultList;
            }
            boolean change = ftpClient.changeWorkingDirectory(path);
            if(change){
                FTPFile[] ftpFiles = ftpClient.listFiles();
                for (FTPFile ftpFile : ftpFiles) {
                    if(ftpFile.isDirectory()){
                        System.out.println(ftpFile.getName());
                        resultList.add(path+"/"+ftpFile.getName());
                        continue;
                    }
                }
                return resultList;
            }
        }catch (IOException e){
            e.printStackTrace();
        }
        return null;
    }

    /*
     * Description:获取ftp指定目录下的文件名称
     *
     * @param url FTP 服务器hostname
     * @param port FTP服务器端口
     * @param username FTP登录密码
     * @param password FTP登录密码
     * @param path FTP服务器保存目录,如果是根目录则为“/”
     * @return 文件夹名称集合
     * */
    public static List<String> getFileNameList(String url, Integer port, String username, String password, String path) {
        List<String> resultList = new ArrayList<>();
        int reply;
        try{
            ftpClient.connect(url,port);

            ftpClient.login(username,password);
            ftpClient.setControlEncoding(encoding);

            //检查是否连接成功
            reply = ftpClient.getReplyCode();
            if(!FTPReply.isPositiveCompletion(reply)){
                logger.info("连接失败");
                ftpClient.disconnect();
                return resultList;
            }
            boolean change = ftpClient.changeWorkingDirectory(path);
            if(change){
                FTPFile[] ftpFiles = ftpClient.listFiles();
                for (FTPFile ftpFile : ftpFiles) {
                    if(ftpFile.isFile()){
                        System.out.println(ftpFile.getName());
                        resultList.add(path+"/"+ftpFile.getName());
                        continue;
                    }
                }
                return resultList;
            }
        }catch (IOException e){
            e.printStackTrace();
        }
        return null;
    }

    

    //删除已存在文件
    private static boolean deleteOldFile(String url, int port, String username, String password,String path, String destFileName) throws IOException {
        ftpClient.connect(url, port);
        ftpClient.login(username, password);
        ftpClient.setControlEncoding(encoding);
        //检查是否连接成功
        int reply = ftpClient.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftpClient.disconnect();
            logger.info("文件服务器连接失败");
            return false;
        }
        boolean flag = false;
        boolean b = ftpClient.changeWorkingDirectory(path);
        FTPFile[] fs = ftpClient.listFiles();
        //判断文件是否存在,存在则删除原文件,然后重命名新文件
        if (null!=fs && fs.length > 0) {
            if (ftpClient.dele(destFileName) > 0) {
                flag = true;
                logger.info("删除已存在文件成功");
            } else {
                flag = false;
            }
        } else {
            flag = true;
        }

        return flag;
    }

    //文件重命名
    private static boolean reName(String url, int port, String username, String password, String uid, String destDir, String destFileName) {
        int reply;
        boolean rename = false;
        try {
            ftpClient.connect(url, port);
            ftpClient.login(username, password);
            ftpClient.setControlEncoding(encoding);
            //检查是否连接成功
            reply = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.disconnect();
                logger.info("文件服务器连接失败");
                return false;
            }
            boolean b = ftpClient.changeWorkingDirectory(destDir);
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            if (!b) {
                String[] split = destDir.split("/");
                String tempPath = "";
                for (String str : split) {
                    if (StrUtil.isEmpty(str)) {
                        continue;
                    }
                    tempPath += "/" + str;
                    if (!ftpClient.changeWorkingDirectory(tempPath)) {
                        if (!ftpClient.makeDirectory(tempPath)) {
                            logger.info("文件目录创建失败");
                        }
                    }
                }
            }
            System.out.println(b);
            String s = ftpClient.printWorkingDirectory();
            System.out.println(s);
            //文件重命名
            String fileName = uid + destFileName.substring(destFileName.lastIndexOf("."));
            rename = ftpClient.rename(tempPath + "/" + fileName, destDir + "/" + destFileName);
            ftpClient.logout();
            return rename;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


    //文件重命名
    public static boolean reName(String ftpIp, Integer ftpPort, String ftpUserName, String ftpPassword, String path_old, String guid_old, String path_new, String guid_new) {
        int reply;
        boolean rename = false;
        try {
            ftpClient.connect(ftpIp, ftpPort);
            ftpClient.login(ftpUserName, ftpPassword);
            ftpClient.setControlEncoding(encoding);
            //检查是否连接成功
            reply = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.disconnect();
                logger.info("文件服务器连接失败");
                return false;
            }
            boolean b = ftpClient.changeWorkingDirectory(path_new);
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            if (!b) {
                String[] split = path_new.split("/");
                String tempPath = "";
                for (String str : split) {
                    if (StrUtil.isEmpty(str)) {
                        continue;
                    }
                    tempPath += "/" + str;
                    if (!ftpClient.changeWorkingDirectory(tempPath)) {
                        if (!ftpClient.makeDirectory(tempPath)) {
                            logger.info("文件目录创建失败");
                        }
                    }
                }
            }
            //文件重命名
            rename = ftpClient.rename(path_old + "/" + guid_old, path_new + "/" + guid_new);
            ftpClient.logout();
            return rename;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static Boolean getFile(String url, Integer port, String username, String password, String remotePath, String fileName) {
        boolean result = false;
        try {
            int reply;
            ftpClient.setControlEncoding(encoding);

            ftpClient.connect(url,port);
            ftpClient.login(username,password);

            reply = ftpClient.getReplyCode();
            if(!FTPReply.isPositiveCompletion(reply)){
                ftpClient.disconnect();
                System.err.println("FTP server refused connection");
                return result;
            }

            //设置文件传输类型为二进制
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            //转移到FTP服务器目录至指定的目录下
            ftpClient.changeWorkingDirectory(remotePath);

            //获取文件列表
            FTPFile[] fs = ftpClient.listFiles();
            for (FTPFile ff : fs){
                if(ff.getName().equals(fileName)){
                    result = true;
                }
            }
            ftpClient.logout();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(ftpClient.isConnected()){
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    public static boolean downZykFileTwo(String url, int port, String username, String password, String remotePath, String fileName,String path_new,String guid_new){
        InputStream tempIn = null;
        InputStream inputStream = null;
        byte[] bytes = null;
        boolean result = false;
        try {
            int reply;
            ftpClient.setControlEncoding(encoding);

            ftpClient.connect(url,port);
            ftpClient.login(username,password);

            reply = ftpClient.getReplyCode();
            if(!FTPReply.isPositiveCompletion(reply)){
                ftpClient.disconnect();
                System.err.println("FTP server refused connection");
                return result;
            }

            //设置文件传输类型为二进制
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            //转移到FTP服务器目录至指定的目录下
            ftpClient.changeWorkingDirectory(remotePath);
            //获取文件列表
            FTPFile[] fs = ftpClient.listFiles();
            for (FTPFile ff : fs){
                if(ff.getName().equals(fileName)){
                    tempIn = ftpClient.retrieveFileStream(ff.getName());
                    ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
                    byte[] buf = new byte[204800];
                    int bufsize = 0;
                    while ((bufsize = tempIn.read(buf,0,buf.length))!=-1){
                        byteOut.write(buf,0,bufsize);
                    }
                    bytes = byteOut.toByteArray();
                    byteOut.close();
                    tempIn.close();
                }
            }
            ftpClient.logout();
            inputStream = new ByteArrayInputStream(bytes);
            return uploadFile(url, port, username, password, path_new, guid_new, inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(ftpClient.isConnected()){
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    /*
     * Description: 从FTP服务器下载文件
     *
     * @Version1.0
     * @param url FTP服务器hostname
     * @param port FTP服务器端口
     * @param username FTP登录密码
     * @param remotePath FTP服务器上的相对路径
     * @param fileName 要下载的文件名
     *
     * */
    public static InputStream downZykFile(String url, int port, String username, String password, String remotePath, String fileName){
        try {
            int reply;
            ftpClient.setControlEncoding(encoding);

            ftpClient.connect(url,port);
            ftpClient.login(username,password);

            reply = ftpClient.getReplyCode();
            if(!FTPReply.isPositiveCompletion(reply)){
                ftpClient.disconnect();
                System.err.println("FTP server refused connection");
                return null;
            }

            //设置文件传输类型为二进制
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            //转移到FTP服务器目录至指定的目录下
            ftpClient.changeWorkingDirectory(remotePath);
            //获取文件列表
            FTPFile[] fs = ftpClient.listFiles();
            for (FTPFile ff : fs){
                if(ff.getName().equals(fileName)){
                    return ftpClient.retrieveFileStream(ff.getName());
                }
            }
            ftpClient.logout();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(ftpClient.isConnected()){
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值