FTP工具类

FTP工具类

import org.apache.commons.io.IOUtils;
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.springframework.beans.factory.annotation.Value;

import javax.sound.midi.Soundbank;
import java.io.*;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;

/**
     * ftp工具类
     */


        /**
         * ftp下载文件
         * @param ftpPath  ftp服务器路径
         * @param localPath  保存文件的路径
         * @param fileName  文件名称
         * @throws Exception
         */
        public void downFile(String ftpPath,String localPath,String fileName) throws Exception {
            try {
                ftpClient = this.getFTPClient(ftpIp,ftpUserName,ftpPassword,ftpPort);
                ftpClient.setControlEncoding("UTF-8"); // 中文支持
                ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
                ftpClient.enterLocalPassiveMode();
                ftpClient.changeWorkingDirectory(ftpPath);
                File localFile = new File(localPath + File.separatorChar + fileName);
                OutputStream os = new FileOutputStream(localFile);
                ftpClient.retrieveFile(fileName, os);
                os.close();
                ftpClient.logout();

            } catch (FileNotFoundException e) {
                System.out.println("没有找到" + ftpPath + "文件");
                e.printStackTrace();
            } catch (SocketException e) {
                System.out.println("连接FTP失败.");
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("文件读取错误。");
                e.printStackTrace();
            }
        }



        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();
        }
        /**
         * Description: 向FTP服务器上传文件
         * FTP服务器中文件所在路径 格式: ftptest/aa
         * @param fileName ftp文件名称
         * @param input 文件流
         * @return 成功返回true,否则返回false
         */
        public  boolean uploadFile(String ftpPath,String fileName, InputStream input) {
            boolean success = false;
            try {
//                byte[] getData = readInputStream(input);
//                input.read(getData);
//                String str = new String(getData);
//                System.out.println ("打印内容:"+str);
                System.out.println("_____________________________________"+fileName);
                int reply;
                ftpClient = getFTPClient(ftpIp, ftpUserName, ftpPassword, ftpPort);
                reply = ftpClient.getReplyCode();
                if (!FTPReply.isPositiveCompletion(reply)) {
                    ftpClient.disconnect();
                    return success;
                }
                ftpClient.setControlEncoding("UTF-8"); // 中文支持
                ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
                ftpClient.enterLocalPassiveMode();

                if(ftpPath!=null && !"".equals(ftpPath)) {
                    CreateDirecroty(ftpPath); //在ftp服务器中创建文件夹
                }
                ftpClient.changeWorkingDirectory(ftpPath);
                ftpClient.storeFile(fileName, input);
                input.close();
                ftpClient.logout();
                success = true;
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (ftpClient.isConnected()) {
                    try {
                        ftpClient.disconnect();
                    } catch (IOException ioe) {
                    }
                }
            }
            return success;
        }

        /**
         * 获取FTPClient对象
         * @param ftpIp     FTP主机服务器
         * @param ftpPassword FTP 登录密码
         * @param ftpUserName FTP登录用户名
         * @param ftpPort     FTP端口 默认为21
         * @return
         */
        public FTPClient getFTPClient(String ftpIp, String ftpUserName,String ftpPassword, int ftpPort) {
            FTPClient ftpClient = new FTPClient();
            try {
                ftpClient = new FTPClient();
                ftpClient.connect(ftpIp,ftpPort);// 连接FTP服务器
                ftpClient.login(ftpUserName, ftpPassword);// 登陆FTP服务器
                if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                    System.out.println("未连接到FTP,用户名或密码错误。");
                    ftpClient.disconnect();
                } else {
                    System.out.println("FTP连接成功。");
                }
            } catch (SocketException e) {
                e.printStackTrace();
                System.out.println("FTP的IP地址可能错误,请正确配置。");
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("FTP的端口错误,请正确配置。");
            }
            return ftpClient;
        }

        public static byte[] getInputStream(String ftpFileName,String ftpIp,String ftpUserName,String ftpPassword,String ftpProt) {
         String basepath = "";
        try {
            FTPClient ftpClient =  new FTPClient();
            ftpClient.setConnectTimeout(5);

            //连接ftp服务器 参数填服务器的ip
            ftpClient.connect(ftpIp, Integer.valueOf(ftpProt));

            //进行登录 参数分别为账号 密码
            ftpClient.login(ftpUserName, ftpPassword);

            //改变工作目录(按自己需要是否改变)
            //只能选择local_root下已存在的目录
            ftpClient.changeWorkingDirectory(basepath);

            //设置文件类型为二进制文件
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            if ("".equals(basepath)) {
                basepath = "/";
            }
            String dir = new String(basepath.getBytes("GBK"), StandardCharsets.ISO_8859_1);
            // 一定要加上字符集指定,因为获取文件时有中文,会出现乱码而获取不到。
            String fileName = new String(ftpFileName.getBytes("GBK"), StandardCharsets.ISO_8859_1);
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            // 每次数据连接之前,ftp client告诉ftp server开通一个端口来传输数据,ftp server可能每次开启不同的端口来传输数据,
            // 但是在Linux上,由于安全限制,可能某些端口没有开启,所以就出现阻塞。
            ftpClient.enterLocalPassiveMode();
            InputStream inputStream = ftpClient.retrieveFileStream(fileName);
            byte[] bytes = IOUtils.toByteArray(inputStream);
            inputStream.close();
            ftpClient.getReply();
            ftpClient.logout();
            return bytes;
        } catch (Exception e) {
            System.out.println( e.toString());
            return null;
        }
    }


    public static byte[] getInputStreamgfkh(String ftpFileName,String ftpIp,String ftpUserName,String ftpPassword,String ftpProt) {
        String basepath = "";
        try {
            FTPClient ftpClient =  new FTPClient();
            ftpClient.setConnectTimeout(5);

            //连接ftp服务器 参数填服务器的ip
            ftpClient.connect(ftpIp, Integer.valueOf(ftpProt));

            //进行登录 参数分别为账号 密码
            ftpClient.login(ftpUserName, ftpPassword);

            //改变工作目录(按自己需要是否改变)
            //只能选择local_root下已存在的目录
            ftpClient.changeWorkingDirectory(basepath);

            //设置文件类型为二进制文件
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            if ("".equals(basepath)) {
                basepath = "/";
            }
            String dir = new String(basepath.getBytes("GBK"), StandardCharsets.ISO_8859_1);
            // 一定要加上字符集指定,因为获取文件时有中文,会出现乱码而获取不到。
            String fileName = new String(ftpFileName.getBytes("GBK"), StandardCharsets.ISO_8859_1);
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            // 每次数据连接之前,ftp client告诉ftp server开通一个端口来传输数据,ftp server可能每次开启不同的端口来传输数据,
            // 但是在Linux上,由于安全限制,可能某些端口没有开启,所以就出现阻塞。
            ftpClient.enterLocalPassiveMode();
            InputStream inputStream = ftpClient.retrieveFileStream(fileName);
            byte[] bytes = IOUtils.toByteArray(inputStream);
            inputStream.close();
            ftpClient.getReply();
            ftpClient.logout();
            return bytes;
        } catch (Exception e) {
            System.out.println( e.toString());
            return null;
        }
    }


        //改变目录路径
        public boolean changeWorkingDirectory(String directory) {
            boolean flag = true;
            try {
                flag = ftpClient.changeWorkingDirectory(directory);
                if (flag) {
                    System.out.println("进入文件夹" + directory + " 成功!");

                } else {
                    System.out.println("进入文件夹" + directory + " 失败!开始创建文件夹");
                }
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
            return flag;
        }

        //创建多层目录文件,如果有ftp服务器已存在该文件,则不创建,如果无,则创建
        public boolean CreateDirecroty(String remote) throws IOException {
            boolean success = true;
            String directory = remote + "/";
            // 如果远程目录不存在,则递归创建远程服务器目录
            if (!directory.equalsIgnoreCase("/") && !changeWorkingDirectory(new String(directory))) {
                int start = 0;
                int end = 0;
                if (directory.startsWith("/")) {
                    start = 1;
                } else {
                    start = 0;
                }
                end = directory.indexOf("/", start);
                String path = "";
                String paths = "";
                while (true) {
                    String subDirectory = new String(remote.substring(start, end).getBytes("GBK"), "iso-8859-1");
                    path = path + "/" + subDirectory;
                    if (!existFile(path)) {
                        if (makeDirectory(subDirectory)) {
                            changeWorkingDirectory(subDirectory);
                        } else {
                            System.out.println("创建目录[" + subDirectory + "]失败");
                            changeWorkingDirectory(subDirectory);
                        }
                    } else {
                        changeWorkingDirectory(subDirectory);
                    }

                    paths = paths + "/" + subDirectory;
                    start = end + 1;
                    end = directory.indexOf("/", start);
                    // 检查所有目录是否创建完毕
                    if (end <= start) {
                        break;
                    }
                }
            }
            return success;
        }

        //判断ftp服务器文件是否存在
        public boolean existFile(String path) throws IOException {
            boolean flag = false;
            FTPFile[] ftpFileArr = ftpClient.listFiles(path);
            if (ftpFileArr.length > 0) {
                flag = true;
            }
            return flag;
        }
        //创建目录
        public boolean makeDirectory(String dir) {
            boolean flag = true;
            try {
                flag = ftpClient.makeDirectory(dir);
                if (flag) {
                    System.out.println("创建文件夹" + dir + " 成功!");

                } else {
                    System.out.println("创建文件夹" + dir + " 失败!");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return flag;
        }



        public String getFtpIp() {return ftpIp;}
        public void setFtpIp(String ftpIp) {this.ftpIp = ftpIp;}
        public String getFtpUserName() {return ftpUserName;}
        public void setFtpUserName(String ftpUserName) {this.ftpUserName = ftpUserName;}
        public String getFtpPassword() {return ftpPassword;}
        public void setFtpPassword(String ftpPassword) {this.ftpPassword = ftpPassword;}
        public Integer getFtpPort() {return ftpPort;}
        public void setFtpPort(Integer ftpPort) {this.ftpPort = ftpPort;}
        public Integer getHttpPort() {return httpPort;}
        public void setHttpPort(Integer httpPort) {this.httpPort = httpPort;}
        public FTPClient getFtpClient() {return ftpClient;}
        public void setFtpClient(FTPClient ftpClient) {this.ftpClient = ftpClient;}

        public FtpUtil(String ftpIp, String ftpUserName, String ftpPassword, Integer ftpPort, Integer httpPort) {
            this.ftpIp = ftpIp;
            this.ftpUserName = ftpUserName;
            this.ftpPassword = ftpPassword;
            this.ftpPort = ftpPort;
            this.httpPort = httpPort;
        }

        public FtpUtil() {
        }
        public FTPClient geta(){
            return getFTPClient(ftpIp, ftpUserName, ftpPassword, ftpPort);
        }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个JavaFTP工具类的示例代码: ```java import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPReply; import java.io.*; public class FTPUtil { private FTPClient ftpClient; public FTPUtil() { ftpClient = new FTPClient(); } public boolean connect(String server, int port, String user, String password) { try { ftpClient.connect(server, port); int replyCode = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(replyCode)) { return false; } boolean success = ftpClient.login(user, password); if (!success) { return false; } ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); return true; } catch (IOException e) { e.printStackTrace(); return false; } } public boolean uploadFile(String localFilePath, String remoteFilePath) { try (InputStream inputStream = new FileInputStream(localFilePath)) { return ftpClient.storeFile(remoteFilePath, inputStream); } catch (IOException e) { e.printStackTrace(); return false; } } public boolean downloadFile(String remoteFilePath, String localFilePath) { try (OutputStream outputStream = new FileOutputStream(localFilePath)) { return ftpClient.retrieveFile(remoteFilePath, outputStream); } catch (IOException e) { e.printStackTrace(); return false; } } public boolean disconnect() { try { ftpClient.logout(); ftpClient.disconnect(); return true; } catch (IOException e) { e.printStackTrace(); return false; } } } ``` 使用该工具类,你可以连接到FTP服务器,上传文件和下载文件。你需要引入Apache Commons Net库,该库提供了FTP客户端的实现。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值