开启FTP客户端(编程)

说明

这次编写的是FTP客户端的编程代码。在这个项目中,应用了比较多的jar包,这一点让编程变得简单,也让头脑变得简单(悲伤)。

FTPClient的API

ftp中ftpClient类的API

主要源码

package com.chen.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Scanner;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;

import com.chen.model.CHENFTPFile;
import com.chen.model.CHENFTPUser;
import com.chen.util.CHENScanner;

/**
 * @description this is the ftpsevice
 * 这是一个 ftp服务层,主要作用就是翻译用户的输入然后调用工具类,
 * 只做了一些基本的检验
 * @time 2016/6/6
 * @author CHEN
 *
 */
public class CHENFTPService {

       private Logger logger = Logger.getLogger (CHENFTPService.class);

       /**
       * 用户登陆
       *
       * @return
       */
       public boolean loginUser(CHENFTPUser user) {
            InetAddress netAddress=null ;
             try {
                   netAddress = InetAddress.getLocalHost();
                   logger.info("记录日记\n"
                              + "访问者ip:" +netAddress .getHostName());
            } catch (UnknownHostException e1 ) {
                   logger.info("获取不到客户端主机" );
                   logger.error(e1 .getMessage(),e1);

            } //获得ftp客户端信息
             boolean flag = false;
            Scanner scanner = CHENScanner.getScanner();
            System. out.print("ftp> open " );
             user.setHostname(scanner .next());
            System. out.println("连接到" + user.getHostname());
            System. out.print("端口号<" + user.getHostname() + ">:");
             try {
                   user.setPort(scanner .nextInt());
            } catch (Exception e ) {
                  System. out.println("ftp> 参数错误,连接默认端口21" );
                   user.setPort(21);
            }
            System. out.print("用户 <" + user.getHostname() + ">:");
             user.setUsername(scanner .next());
            System. out.print("密码<" + user.getHostname() + ">:");
             user.setPassword(scanner .next());

            FTPClient ftpClient = new FTPClient();
             ftpClient.setControlEncoding("UTF-8" );// 设置编码
             try {
                   // 链接服务器
                   ftpClient.connect(user .getHostname(), user.getPort());
                   // 登陆服务器
                   ftpClient.login(user .getUsername(), user.getPassword());
                   // 判断是否成功登陆
                   if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                         flag = true ;
                         user.setFtpClient(ftpClient );
                         user.setLogin(true);
                         user.setWorkPath("/" );
                        System. out.println("登陆成功" );

                  } else {
                        System. out.println("登陆失败" );
                  }

            } catch (SocketException e ) {
                   logger.error(e .getMessage(),e);
            } catch (IOException e ) {
                   logger.error(e .getMessage(),e);
            }

             return flag ;
      }

       /**
       * 读取当前目录所有的文件
       *
       * @return
       * @throws IOException
       */
       public boolean readAllFile(CHENFTPUser user) {
             boolean flag = false;
            FTPClient ftpClient = user .getFtpClient();
            FTPFile[] files;
             try {
                   files = ftpClient .listFiles(user.getWorkPath());
                   for (FTPFile file : files) {
                         if (file .isFile()) {
                              System. out.println(user .getSimpleDateFormat(file
                                          .getTimestamp()) + "    " + file.getName());
                        } else if (file .isDirectory()) {
                              System. out.println(user .getSimpleDateFormat(file
                                          .getTimestamp()) + "    <dir>  /" + file.getName());
                        } else {
                              System. out.println("no file or have been broken");
                        }
                  }
            } catch (IOException e ) {
                   logger.error(e .getMessage(), e);
            }

             return flag ;
      }

       /**
       * 下载一个文件
       * @param user
       * @return
       */
       public boolean getOneFile(CHENFTPUser user) {
             boolean flag = false;
            Scanner scanner = CHENScanner.getScanner();
            FTPClient ftpClient = user .getFtpClient();
            System. out.print("远程文件    " );
            CHENFTPFile file = new CHENFTPFile();
             file.setOldFileURL(scanner .next());
            System. out.print("本地文件    " );
             file.setNewFileURL(scanner .next());

             // 遍历文件
             try {
                   // 切换到相应的文件夹
                   ftpClient.changeWorkingDirectory(user .getWorkPath());
                   // 下载文件
                  File localFile = new File(file.getNewFileURL());
                  OutputStream os = new FileOutputStream(localFile );
                   ftpClient.retrieveFile(file .getOldFileURL(), os);
                   os.close();

            } catch (IOException e ) {
                   logger.error(e .getMessage(), e);
            }
             return flag ;
      }

       /**
       * 上传一个文件
       * @param user
       * @return
       */
       public boolean sendOneFile(CHENFTPUser user) {
             boolean flag = false;
            Scanner scanner = CHENScanner.getScanner();
            FTPClient ftpClient = user .getFtpClient();
            CHENFTPFile file = new CHENFTPFile();
            System. out.print("远程文件    " );
             file.setNewFileURL(scanner .next());
            System. out.print("本地文件    " );
             file.setOldFileURL(scanner .next());

             // 分析远程文件
            String fileUrl = file .getNewFileURL();
            String filePath = null ;
             try {
                   filePath = fileUrl .substring(0, fileUrl.indexOf("/" ));// 获得父级路径
                   if ("/" .equals(filePath) || filePath.length() == 0) {
                         throw new Exception();
                  }
            } catch (Exception e ) {
                   filePath = user .getWorkPath();// 换成当前工作区
            }
            String fileName = fileUrl .substring(fileUrl.indexOf( "/") + 1);// 获得文件名

             // 上传文件
             try {
                  InputStream is = new FileInputStream(new File(file.getOldFileURL()));
                   // 准备服务器
                   ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
                   ftpClient.makeDirectory(filePath );
                   ftpClient.changeWorkingDirectory(filePath );
                   ftpClient.storeFile(fileName , is );
                   is.close();
                   flag = true ;
            } catch (FileNotFoundException e ) {
                   logger.error(e .getMessage(), e);
            } catch (IOException e ) {
                   logger.error(e .getMessage(), e);
            }
             return flag ;
      }

       /**
       * 修改工作区间
       *
       * @param user
       */
       public void changDirectory(CHENFTPUser user) {
            Scanner scanner = CHENScanner.getScanner();
            String tempPath = "/" + scanner.next();
            FTPClient ftpClient = user .getFtpClient();
             try {
                   ftpClient.makeDirectory(tempPath );
            } catch (IOException e ) {
                   logger.error(e .getMessage(), e);
            }
             user.setWorkPath(tempPath );// 输入示例: temp
             try {
                   ftpClient.changeWorkingDirectory(tempPath );
                   user.setFtpClient(ftpClient );
            } catch (IOException e ) {
                   logger.error(e .getMessage(), e);
            }

      }

       /**
       * 自动登陆
       *
       * @param user
       */
       public void loginUserByAuto(CHENFTPUser user) {
             boolean flag = false;
            System. out.print("ftp> open " );
             // 默认端口号 21
             user.setHostname("10.10.121.8" );
             user.setPort(21);
             user.setUsername("CHEN" );
             user.setPassword("CHEN0422" );

            FTPClient ftpClient = new FTPClient();
             ftpClient.setControlEncoding("UTF-8" );// 设置编码
             try {
                   // 链接服务器
                   ftpClient.connect(user .getHostname(), user.getPort());
                   // 登陆服务器
                   ftpClient.login(user .getUsername(), user.getPassword());
                   // 判断是否成功登陆
                   if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                         flag = true ;
                         user.setFtpClient(ftpClient );
                         user.setLogin(true);
                         user.setWorkPath("/" );
                        System. out.println("登陆成功" );

                  } else {
                        System. out.println("登陆失败" );
                  }
            } catch (SocketException e ) {
                   // logger.error(e.getMessage(),e);
            } catch (IOException e ) {
                   // logger.error(e.getMessage(),e);
            }

      }

       /**
       * 删除文件
       *
       * @param user
       */
       public void deleteOneFile(CHENFTPUser user) {
             boolean flag = false;
            Scanner scanner = CHENScanner.getScanner();
            FTPClient ftpClient = user .getFtpClient();

             try {
                   ftpClient.changeWorkingDirectory(user .getWorkPath());
                   ftpClient.deleteFile(scanner .next());
            } catch (IOException e ) {
                   logger.error(e .getMessage(), e);
            }

      }

       /**
       * 断开链接
       *
       * @param user
       */
       public boolean disConnection(CHENFTPUser user) {
             try {
                   user.getFtpClient().disconnect();
                   // 初始化
                   user.setFtpClient(null);
                   user.setHostname("" );
                   user.setPort(0);
                   user.setLogin(false);
                   user.setUsername("" );
                   user.setPassword("" );
                   user.setWorkPath("/" );
            } catch (IOException e ) {
                   logger.error(e .getMessage(), e);
            }
             return true ;

      }

}

附言

对于上一篇开启FTP服务器(编程),我更多的是研究他的返回码和协议的内容,而在这个项目中,更多的是对
org.apache.commons.net.ftp.FTPClient 这个类的研究。

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐