FTP工具类(附:FTP服务器的配置文件)

首先附上FTP服务器的配置文件,因为服务器配置有问题可能导致工具类连接不成功:

# Example config file /etc/vsftpd/vsftpd.conf
#
# The default compiled in settings are fairly paranoid. This sample file
# loosens things up a bit, to make the ftp daemon more usable.
# Please see vsftpd.conf.5 for all compiled in defaults.
#
# READ THIS: This example file is NOT an exhaustive list of vsftpd options.
# Please read the vsftpd.conf.5 manual page to get a full idea of vsftpd's
# capabilities.
#
# Allow anonymous FTP? (Beware - allowed by default if you comment this out).
anonymous_enable=YES
#
# Uncomment this to allow local users to log in.
# When SELinux is enforcing check for SE bool ftp_home_dir
local_enable=YES
#
# Uncomment this to enable any form of FTP write command.
write_enable=YES
#
# Default umask for local users is 077. You may wish to change this to 022,
# if your users expect that (022 is used by most other ftpd's)
local_umask=022
#
# Uncomment this to allow the anonymous FTP user to upload files. This only
# has an effect if the above global write enable is activated. Also, you will
# obviously need to create a directory writable by the FTP user.
# When SELinux is enforcing check for SE bool allow_ftpd_anon_write, allow_ftpd_full_access
anon_upload_enable=YES
#
# Uncomment this if you want the anonymous FTP user to be able to create
# new directories.
anon_mkdir_write_enable=YES
#
# Activate directory messages - messages given to remote users when they
# go into a certain directory.
dirmessage_enable=YES
#
# Activate logging of uploads/downloads.
xferlog_enable=YES
#
# Make sure PORT transfer connections originate from port 20 (ftp-data).
connect_from_port_20=YES
#
# If you want, you can arrange for uploaded anonymous files to be owned by
# a different user. Note! Using "root" for uploaded files is not
# recommended!
#chown_uploads=YES
#chown_username=whoever
#
# You may override where the log file goes if you like. The default is shown
# below.
#xferlog_file=/var/log/xferlog
#
# If you want, you can have your log file in standard ftpd xferlog format.
# Note that the default log file location is /var/log/xferlog in this case.
xferlog_std_format=YES
#
# You may change the default value for timing out an idle session.
idle_session_timeout=600
#
# You may change the default value for timing out a data connection.
data_connection_timeout=120
#
# It is recommended that you define on your system a unique user which the
# ftp server can use as a totally isolated and unprivileged user.
#nopriv_user=ftpsecure
nopriv_user=nobody
#
# Enable this and the server will recognise asynchronous ABOR requests. Not
# recommended for security (the code is non-trivial). Not enabling it,
# however, may confuse older FTP clients.
#async_abor_enable=YES
#
# By default the server will pretend to allow ASCII mode but in fact ignore
# the request. Turn on the below options to have the server actually do ASCII
# mangling on files when in ASCII mode. The vsftpd.conf(5) man page explains
# the behaviour when these options are disabled.
# Beware that on some FTP servers, ASCII support allows a denial of service
# attack (DoS) via the command "SIZE /big/file" in ASCII mode. vsftpd
# predicted this attack and has always been safe, reporting the size of the
# raw file.
# ASCII mangling is a horrible feature of the protocol.
#ascii_upload_enable=YES
#ascii_download_enable=YES
#
# You may fully customise the login banner string:
#ftpd_banner=Welcome to blah FTP service.
#
# You may specify a file of disallowed anonymous e-mail addresses. Apparently
# useful for combatting certain DoS attacks.
#deny_email_enable=YES
# (default follows)
#banned_email_file=/etc/vsftpd/banned_emails
#
# You may specify an explicit list of local users to chroot() to their home
# directory. If chroot_local_user is YES, then this list becomes a list of
# users to NOT chroot().
# (Warning! chroot'ing can be very dangerous. If using chroot, make sure that
# the user does not have write access to the top level directory within the
# chroot)
chroot_local_user=NO
chroot_list_enable=YES
# (default follows)
chroot_list_file=/etc/vsftpd/chroot_list
#
# You may activate the "-R" option to the builtin ls. This is disabled by
# default to avoid remote users being able to cause excessive I/O on large
# sites. However, some broken FTP clients such as "ncftp" and "mirror" assume
# the presence of the "-R" option, so there is a strong case for enabling it.
#ls_recurse_enable=YES
#
#
#使用pam托管的账号
pam_service_name=vsftpd
tcp_wrappers=YES
#使用被动模式连接
pasv_enable=YES
#被动模式超时时间
accept_timeout=60
#被动模式所使用的端口范围
pasv_min_port=65400
pasv_max_port=65410
#使用user_list文件(开启管理user_list里的用户)
userlist_enable=YES
#不禁止user_list里的用户登录
userlist_deny=NO
#user_list文件地址
userlist_file=/etc/vsftpd/user_list
listen_port=21
# 当启用listen指令时 vsftpd以独立模式运行并侦听IPv4的sockets 此指令不能与listen_ipv6指令一起使用
listen=YES
#此指令允许侦听IPv6套接字。默认情况下,
#监听IPv6将接受来自IPv6和IPv4客户端的连接,不需要同时监听IPv4和IPv6的sockets。
#如果您想这样做(也许是因为您想监听特定的地址),那么您必须使用两个配置文件运行vsftpd的两个副本。
#确保其中一个监听选项被开启!!
listen_ipv6=NO
#开放用户账号登陆
#guest_enable=YES
#guest_username=ftp
#限制用户的上传下载速度,0为不限制,单位: bytes/秒
local_max_rate=0
#如果启用了限定用户在其主目录下需要添加这个配置,解决报错 500
allow_writeable_chroot=YES

在pom.xml文件中添加依赖

<!--FTP包-->
		<dependency>
			<groupId>commons-net</groupId>
			<artifactId>commons-net</artifactId>
			<version>3.5</version>
		</dependency>

FTP工具类

package util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
/**
 * 
 * FTP工具类
 * @className FtpUtil
 * @author jeason
 * @date 2019年8月29日
 */
public class FtpUtil {
        //ftp服务器地址
        private static final String HOSTNAME = Global.getConfig("ftp.hostname");
        //ftp服务器端口号默认为21
        private static final Integer PORT = Integer.valueOf(Global.getConfig("ftp.port"));
        //ftp登录账号
        private static final String USERNAME = Global.getConfig("ftp.username");
        //ftp登录密码
        private static final String PASSWORD = Global.getConfig("ftp.password");
        
        private static FTPClient ftpClient = null;

    /**
     * 初始化ftp服务器
     */
    public static void initFtpClient() {
        try {
            ftpClient = new FTPClient();
            System.out.println("ftp连接中...:"+HOSTNAME+":"+PORT);
            ftpClient.connect(HOSTNAME, PORT); //连接ftp服务器
            ftpClient.login(USERNAME, PASSWORD); //登录ftp服务器
            int replyCode = ftpClient.getReplyCode();
            if(FTPReply.isPositiveCompletion(replyCode)) {
                System.out.println("ftp连接成功...replyCode:" + replyCode);
            }else{
                System.out.println("ftp连接失败...replyCode:" + replyCode);
            }
            ftpClient.setControlEncoding("utf-8");
            //这个设置允许被动连接
            //这一句一定要放在ftpClient.login()方法之后,登陆成功才有效,本人已趟坑
            ftpClient.enterLocalPassiveMode();
            ftpClient.setFileType(ftpClient.BINARY_FILE_TYPE);
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 销毁ftp服务器
     */
    public static void destroyFtpClient() {
        try {
            System.out.println("ftp断开连接中...");
            ftpClient.logout();
            if(ftpClient.isConnected()){
                ftpClient.disconnect();
            }
            System.out.println("ftp断开已连接...");
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 上传文件
     * @param pathname ftp服务保存地址
     * @param fileName 上传到ftp的文件名
     * @param originFileName 待上传文件的名称(绝对地址)
     * @return
     */
    public static boolean uploadFile(String pathname, String fileName,String originFileName){
        boolean flag = false;
        InputStream inputStream = null;
        try{
            initFtpClient();
            System.out.println("开始上传文件");
            inputStream = new FileInputStream(new File(originFileName));
            intoDirectory(pathname);
            flag = ftpClient.storeFile(fileName, inputStream);
            if(flag) {
                System.out.println("上传文件成功");
            }else {
                System.out.println("上传文件失败");
            }
            destroyFtpClient();
        }catch (Exception e) {
            System.out.println("上传文件失败");
            e.printStackTrace();
        }finally{
            if(null != inputStream){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return flag;
    }

    /**
     * 上传文件
     * @param pathname ftp服务保存地址
     * @param fileName 上传到ftp的文件名
     * @param inputStream 输入文件流
     * @return
     */
    public static boolean uploadFile(String pathname, String fileName,InputStream inputStream){
        boolean flag = false;
        try{
            initFtpClient();
            System.out.println("开始上传文件");
            intoDirectory(pathname);
            flag = ftpClient.storeFile(fileName, inputStream);
            if(flag) {
                System.out.println("上传文件成功");
            }else {
                System.out.println("上传文件失败");
            }
            destroyFtpClient();
        }catch (Exception e) {
            System.out.println("上传文件失败");
            e.printStackTrace();
        }finally{
            if(null != inputStream){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return flag;
    }

    /**
     * 进入directory目录,没有则逐层创建
     * @param directory 目录路径
     * @return
     */
    public static boolean intoDirectory(String directory){
        boolean flag = true;
        try {
            if(ftpClient.changeWorkingDirectory(directory)){
                System.out.println("进入" + directory + "目录成功!");
                System.out.println("当前工作目录:" + ftpClient.printWorkingDirectory());
                return true;
            }
            if(directory.startsWith("/")){
                if(ftpClient.changeWorkingDirectory("/")){
                    System.out.println("进入/目录成功!");
                    System.out.println("当前工作目录:" + ftpClient.printWorkingDirectory());
                    String subDirectory = directory.substring(1);
                    flag = intoSubDirectory(subDirectory);
                }else {
                    System.out.println("进入/目录失败!");
                    System.out.println("进入" + directory + "目录失败!");
                    System.out.println("当前工作目录:" + ftpClient.printWorkingDirectory());
                    return false;
                }
            }else {
                flag = intoSubDirectory(directory);
            }
        }catch (IOException e){
            flag = false;
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 进入子目录,没有则逐层创建
     * @param subDirectory 子目录路径
     * @return
     */
    public static boolean intoSubDirectory(String subDirectory){
        boolean flag = true;
        try {
            String[] everyDir = subDirectory.split("/");
            for (String dir : everyDir) {
                if(ftpClient.changeWorkingDirectory(dir)){
                    System.out.println("进入" + dir + "目录成功!");
                    System.out.println("当前工作目录:"+ftpClient.printWorkingDirectory());
                }else {
                    System.out.println("开始创建" + dir + "目录");
                    if(ftpClient.makeDirectory(dir)){
                        System.out.println("创建" + dir + "目录成功!");
                        if(ftpClient.changeWorkingDirectory(dir)){
                            System.out.println("进入" + dir + "目录成功!");
                            System.out.println("当前工作目录:"+ftpClient.printWorkingDirectory());
                        }else {
                            System.out.println("进入" + dir + "目录失败!");
                            System.out.println("进入" + subDirectory + "目录失败!");
                            System.out.println("当前工作目录:"+ftpClient.printWorkingDirectory());
                            flag = false;
                            break;
                        }
                    }else {
                        System.out.println("创建" + dir + "目录失败!");
                        System.out.println("进入" + subDirectory + "目录失败!");
                        System.out.println("当前工作目录:"+ftpClient.printWorkingDirectory());
                        flag = false;
                        break;
                    }
                }
            }
        }catch (IOException e){
            flag = false;
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 判断ftp服务器文件是否存在
     * @param filePath 文件路径
     * @return
     */
    public static boolean existFile(String filePath){
        boolean flag = false;
        try{
            FTPFile[] ftpFileArr = ftpClient.listFiles(filePath);
            flag = ftpFileArr.length > 0;
        }catch (IOException e){
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 下载文件
     * @param pathname FTP服务器文件目录
     * @param filename 文件名称
     * @param localpath 下载后的文件路径
     * @return
     */
    public static boolean downloadFile(String pathname, String filename, String localpath){
        boolean flag = false;
        OutputStream os=null;
        try {
            System.out.println("开始下载文件");
            initFtpClient();
            //切换FTP目录
            ftpClient.changeWorkingDirectory(pathname);
            FTPFile[] ftpFiles = ftpClient.listFiles();
            for(FTPFile file : ftpFiles){
                if(filename.equalsIgnoreCase(file.getName())){
                    File localFile = new File(localpath + "/" + file.getName());
                    os = new FileOutputStream(localFile);
                    ftpClient.retrieveFile(file.getName(), os);
                    os.close();
                }
            }
            ftpClient.logout();
            flag = true;
            System.out.println("下载文件成功");
        } catch (Exception e) {
            System.out.println("下载文件失败");
            e.printStackTrace();
        } finally{
            if(ftpClient.isConnected()){
                try{
                    ftpClient.disconnect();
                }catch(IOException e){
                    e.printStackTrace();
                }
            }
            if(null != os){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return flag;
    }

    /**
     * 删除文件
     * @param pathname FTP服务器保存目录
     * @param filename 要删除的文件名称
     * @return
     */
    public boolean deleteFile(String pathname, String filename){
        boolean flag = false;
        try {
            System.out.println("开始删除文件");
            initFtpClient();
            //切换FTP目录
            ftpClient.changeWorkingDirectory(pathname);
            ftpClient.dele(filename);
            ftpClient.logout();
            flag = true;
            System.out.println("删除文件成功");
        } catch (Exception e) {
            System.out.println("删除文件失败");
            e.printStackTrace();
        } finally {
            if(ftpClient.isConnected()){
                try{
                    ftpClient.disconnect();
                }catch(IOException e){
                    e.printStackTrace();
                }
            }
        }
        return flag;
    }

    public static void main(String[] args) {
        initFtpClient();
        intoDirectory("/home/code/test");
        destroyFtpClient();
    }
}

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值