当前位置: 移动技术网 > IT编程>开发语言>Java > Spring FTP上传下载工具类遇到问题小结

Spring FTP上传下载工具类遇到问题小结

2019年07月19日  | 移动技术网IT编程  | 我要评论

死心替身,华中师范大学汉口分校分数线,泰州采购

前言

最近在项目中需要和ftp服务器进行交互,在网上找了一下关于ftp上传下载的工具类,大致有两种。

  第一种是单例模式的类。

  第二种是另外定义一个service,直接通过service来实现ftp的上传下载。

  这两种感觉都有利弊。

  第一种实现了代码复用,但是配置信息全需要写在类中,维护比较复杂。

  第二种如果是spring框架,可以通过propertis文件,动态的注入配置信息,但是又不能代码复用。

  所以我打算自己实现一个工具类,来把上面的两种优点进行整合。顺便把一些上传过程中一些常见的问题也给解决了。

  因为我使用的是spring框架,如果把工具类声明为bean给spring管理,他默认就是单例的,所以不需要我再实现单例。并且因为是bean,所以我可以把properties文件的属性注入bean的属性中,实现解耦,下面是具体代码:

package com.cky.util;
import java.io.file;
import java.io.fileoutputstream;
import java.io.ioexception;
import java.io.inputstream;
import java.io.outputstream;
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 org.springframework.stereotype.component;
//使用spring自动生成单例对象,
//@component
public class ftputil {
  //通过properties文件自动注入
  @value("${ftp.host}")
  private string host;  //ftp服务器ip
  @value("${ftp.port}")
  private int port;    //ftp服务器端口
  @value("${ftp.username}")
  private string username;//用户名
  @value("${ftp.password}")
  private string password;//密码
  @value("${ftp.basepath}")
  private string basepath;//存放文件的基本路径
  //测试的时候把这个构造函数打开,设置你的初始值,然后在代码后面的main方法运行测试
  /*public ftputil() {
    //system.out.println(this.tostring());
    host="192.168.100.77";
    port=21;
    username="ftpuser";
    password="ftp54321";
    basepath="/home/ftpuser/";
  }*/
  /**
   * 
   * @param path    上传文件存放在服务器的路径
   * @param filename  上传文件名
   * @param input    输入流
   * @return
   */
  public boolean fileupload(string path,string filename,inputstream input) {
    ftpclient ftp=new ftpclient();
    try {
      ftp.connect(host, port);
      ftp.login(username, password);
      //设置文件编码格式
      ftp.setcontrolencoding("utf-8");
      //ftp通信有两种模式
        //port(主动模式)客户端开通一个新端口(>1024)并通过这个端口发送命令或传输数据,期间服务端只使用他开通的一个端口,例如21
        //pasv(被动模式)客户端向服务端发送一个pasv命令,服务端开启一个新端口(>1024),并使用这个端口与客户端的21端口传输数据
        //由于客户端不可控,防火墙等原因,所以需要由服务端开启端口,需要设置被动模式
      ftp.enterlocalpassivemode();
      //设置传输方式为流方式
      ftp.setfiletransfermode(ftp.stream_transfer_mode);
      //获取状态码,判断是否连接成功
      if(!ftpreply.ispositivecompletion(ftp.getreplycode())) {
        throw new runtimeexception("ftp服务器拒绝连接");
      }
      //转到上传文件的根目录
      if(!ftp.changeworkingdirectory(basepath)) {
        throw new runtimeexception("根目录不存在,需要创建");
      }
      //判断是否存在目录
      if(!ftp.changeworkingdirectory(path)) {
        string[] dirs=path.split("/");
        //创建目录
        for (string dir : dirs) {
          if(null==dir||"".equals(dir)) continue;
          //判断是否存在目录
          if(!ftp.changeworkingdirectory(dir)) {
            //不存在则创建
            if(!ftp.makedirectory(dir)) {
              throw new runtimeexception("子目录创建失败");
            }
            //进入新创建的目录
            ftp.changeworkingdirectory(dir);
          }
        }
        //设置上传文件的类型为二进制类型
        ftp.setfiletype(ftp.binary_file_type);
        //上传文件
        if(!ftp.storefile(filename, input)) {
          return false;
        }
        input.close();
        ftp.logout();
        return true;
      }
    } catch (exception e) {
      throw new runtimeexception(e);
    }finally {
      if(ftp.isconnected()) {
        try {
          ftp.disconnect();
        } catch (ioexception e) {
          throw new runtimeexception(e);
        }
      }
    }
    return false;
  }
  /**
   * 
   * @param filename  文件名,注意!此处文件名为加路径文件名,如:/2015/06/04/aa.jpg
   * @param localpath  存放到本地第地址
   * @return    
   */
  public boolean downloadfile(string filename,string localpath) {
    ftpclient ftp=new ftpclient();
    try {
      ftp.connect(host, port);
      ftp.login(username, password);
      //设置文件编码格式
      ftp.setcontrolencoding("utf-8");
      //ftp通信有两种模式
        //port(主动模式)客户端开通一个新端口(>1024)并通过这个端口发送命令或传输数据,期间服务端只使用他开通的一个端口,例如21
        //pasv(被动模式)客户端向服务端发送一个pasv命令,服务端开启一个新端口(>1024),并使用这个端口与客户端的21端口传输数据
        //由于客户端不可控,防火墙等原因,所以需要由服务端开启端口,需要设置被动模式
      ftp.enterlocalpassivemode();
      //设置传输方式为流方式
      ftp.setfiletransfermode(ftp.stream_transfer_mode);
      //获取状态码,判断是否连接成功
      if(!ftpreply.ispositivecompletion(ftp.getreplycode())) {
        throw new runtimeexception("ftp服务器拒绝连接");
      }
      int index=filename.lastindexof("/");
      //获取文件的路径
      string path=filename.substring(0, index);
      //获取文件名
      string name=filename.substring(index+1);
      //判断是否存在目录
      if(!ftp.changeworkingdirectory(basepath+path)) {
        throw new runtimeexception("文件路径不存在:"+basepath+path);
      }
      //获取该目录所有文件
      ftpfile[] files=ftp.listfiles();
      for (ftpfile file : files) {
        //判断是否有目标文件
        //system.out.println("文件名"+file.getname()+"---"+name);
        if(file.getname().equals(name)) {
          //system.out.println("找到文件");
          //如果找到,将目标文件复制到本地
          file localfile =new file(localpath+"/"+file.getname());
          outputstream out=new fileoutputstream(localfile);
          ftp.retrievefile(file.getname(), out);
          out.close();
        }
      }
      ftp.logout();
      return true;
    } catch (exception e) {
      throw new runtimeexception(e);
    }finally {
      if(ftp.isconnected()) {
        try {
          ftp.disconnect();
        } catch (ioexception e) {
          throw new runtimeexception(e);
        }
      }
    }
  }
  //两个功能其中一个使用的话另一个需要注释
  public static void main(string []args) {
    //上传测试-----------------------------------
    /*fileinputstream in;
    try {
      in=new fileinputstream(new file("c:\\users\\administrator\\desktop\\json.png"));
      ftputil ftputil=new ftputil();
      boolean flag=ftputil.fileupload("/2015/06/04", "aa.jpg", in);
      system.out.println(flag);
    }catch (exception e) {
      e.printstacktrace();
    }finally {
    }*/
    //下载测试--------------------------------------
    string filename="/2015/06/04/aa.jpg";
    string localpath="f:\\";
    ftputil ftputil=new ftputil();
    ftputil.downloadfile(filename, localpath);
  }
  //get set方法自己添加
  //..............
}

具体使用

第一步:配置spring加载properties文件

applicationcontext.xml

<context:property-placeholder location="classpath:*.properties"/>
  ftp.properties
ftp.host=192.168.100.77
ftp.port=21
ftp.username=ftpuser
ftp.password=ftp54321
ftp.basepath=/home/ftpuser/

第二步:将工具类声明为bean

xml方式

<bean id="ftputil" class="com.cky.util.ftputil">
    <property name="host" value="${ftp.host}"></property>
    <property name="port" value="${ftp.port}"></property>
    <property name="username" value="${ftp.username}"></property>
    <property name="password" value="${ftp.password}"></property>
    <property name="basepath" value="${ftp.basepath}"></property>
  </bean>

注解方式,组件扫描

<context:component-scan base-package="com.cky.util"></context:component-scan>

第三部:注入使用

@autowired
  private ftputil ftputil;

总结

以上所述是小编给大家介绍的spring ftp上传下载工具类遇到问题小结,希望对大家有所帮助

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网