当前位置: 移动技术网 > IT编程>开发语言>Java > java基于Apache FTP实现文件上传、下载、修改文件名、删除

java基于Apache FTP实现文件上传、下载、修改文件名、删除

2019年07月22日  | 移动技术网IT编程  | 我要评论
apache ftp 是应用比较广泛的ftp上传客户端工具,它易于操作,代码简略,结构清晰,是做ftp文件客户端管理软件的优先之选。ftp的操作包括:ftp文件上传(断点续

apache ftp 是应用比较广泛的ftp上传客户端工具,它易于操作,代码简略,结构清晰,是做ftp文件客户端管理软件的优先之选。ftp的操作包括:ftp文件上传(断点续传)、ftp文件下载、ftp文件重命名、ftp文件删除,这些操作已经将ftp应用管理的方式发挥的淋漓尽致了,so 我一直都用此种方式来实现ftp文件服务器的管理工作;下附ftp工具代码。

1、ftp文件操作状态枚举类

package com.scengine.wtms.utils.ftp; 
 
public enum ftpstatus 
{ 
  file_exits(0), create_directory_success(1), create_directory_fail(2), upload_from_break_success(3), upload_from_break_faild(4), download_from_break_success(5), download_from_break_faild(6), upload_new_file_success(7), upload_new_file_failed(8), delete_remote_success(9), delete_remote_faild(10),remote_bigger_local(11),remote_smaller_local(12),not_exist_file(13),remote_rename_success(14),remote_rename_faild(15),file_not_unique(16); 
 
  private int status; 
 
  public int getstatus() 
  { 
    return status; 
  } 
 
  public void setstatus(int status) 
  { 
    this.status = status; 
  } 
 
  ftpstatus(int status) 
  { 
    this.status = status; 
  } 
} 

2、ftp文件操作工具代码

package com.scengine.wtms.utils.ftp; 
 
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 java.io.printwriter; 
import javax.servlet.http.httpservletresponse; 
import org.apache.commons.net.printcommandlistener; 
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 com.scengine.wtms.utils.log; 
 
public class ftputils 
{ 
  private ftpclient ftpclient = new ftpclient(); 
 
  /** 
   * 对象构造 设置将过程中使用到的命令输出到控制台 
   */ 
  public ftputils() 
  { 
    this.ftpclient.addprotocolcommandlistener(new printcommandlistener(new printwriter(system.out))); 
  } 
 
  /** 
   * 
   * java编程中用于连接到ftp服务器 
   * 
   * @param hostname 
   *      主机名 
   * 
   * @param port 
   *      端口 
   * 
   * @param username 
   *      用户名 
   * 
   * @param password 
   *      密码 
   * 
   * @return 是否连接成功 
   * 
   * @throws ioexception 
   */ 
 
  public boolean connect(string hostname, int port, string username, string password) throws ioexception 
  { 
 
    ftpclient.connect(hostname, port); 
 
    if (ftpreply.ispositivecompletion(ftpclient.getreplycode())) 
    { 
 
      if (ftpclient.login(username, password)) 
      { 
        return true; 
      } 
    } 
    disconnect(); 
    return false; 
 
  } 
 
  /** 
   * 删除远程ftp文件 
   * 
   * @param remote 
   *      远程文件路径 
   * @return 
   * @throws ioexception 
   */ 
  public ftpstatus delete(string remote) throws ioexception 
  { 
    ftpclient.enterlocalpassivemode(); 
 
    ftpclient.setfiletype(ftp.binary_file_type); 
 
    ftpstatus result = null; 
 
    ftpfile[] files = ftpclient.listfiles(remote); 
    if (files.length == 1) 
    { 
      boolean status = ftpclient.deletefile(remote); 
      result = status ? ftpstatus.delete_remote_success : ftpstatus.delete_remote_faild; 
    } 
    else 
    { 
      result = ftpstatus.not_exist_file; 
    } 
    log.getlogger(this.getclass()).info("ftp服务器文件删除标识:"+result); 
    return result; 
  } 
   
  /** 
   * 重命名远程ftp文件 
   * 
   * @param name 
   *      新远程文件名称(路径-必须保证在同一路径下) 
   *       
   * @param remote 
   *      远程文件路径 
   *       
   * @return 是否成功 
   * 
   * @throws ioexception 
   */ 
  public ftpstatus rename(string name,string remote) throws ioexception 
  { 
    ftpclient.enterlocalpassivemode(); 
 
    ftpclient.setfiletype(ftp.binary_file_type); 
 
    ftpstatus result = null; 
 
    ftpfile[] files = ftpclient.listfiles(remote); 
    if (files.length == 1) 
    { 
      boolean status = ftpclient.rename(remote, name); 
      result = status ? ftpstatus.remote_rename_success : ftpstatus.remote_rename_faild; 
    } 
    else 
    { 
      result = ftpstatus.not_exist_file; 
    } 
    log.getlogger(this.getclass()).info("ftp服务器文件名更新标识:"+result); 
    return result; 
  } 
   
  /** 
   * 
   * 从ftp服务器上下载文件 
   * 
   * @param filename 
   *      下载文件的名字(包括后缀名) 
   * 
   * @param remote 
   *      远程文件路径 
   * 
   * @param local 
   *      本地文件路径 
   * 
   * @return 是否成功 
   * 
   * @throws ioexception 
   */ 
 
  public ftpstatus download(string filename,string remote,httpservletresponse response) throws ioexception 
  { 
    // 开启输出流弹出文件保存路径选择窗口 
    response.setcontenttype("application/octet-stream"); 
     
    response.setcontenttype("application/octet-stream;charset=utf-8"); 
     
    response.setheader("content-disposition", "attachment;filename=" +filename); 
 
    ftpclient.enterlocalpassivemode(); 
 
    ftpclient.setfiletype(ftp.binary_file_type); 
     
    ftpstatus result; 
     
    outputstream out = response.getoutputstream(); 
     
    boolean status = ftpclient.retrievefile(remote, out); 
     
    result=status?ftpstatus.download_from_break_success:ftpstatus.download_from_break_faild; 
     
    log.getlogger(this.getclass()).info("ftp服务器文件下载标识:"+result); 
     
    out.close(); 
     
    return result; 
  } 
 
  /** 
   * 
   * 从ftp服务器上下载文件 
   * 
   * @param remote 
   *      远程文件路径 
   * 
   * @param local 
   *      本地文件路径 
   * 
   * @return 是否成功 
   * 
   * @throws ioexception 
   */ 
 
  @suppresswarnings("resource") 
  public ftpstatus download(string remote, string local) throws ioexception 
  { 
 
    ftpclient.enterlocalpassivemode(); 
 
    ftpclient.setfiletype(ftp.binary_file_type); 
 
    ftpstatus result; 
 
    file f = new file(local); 
 
    ftpfile[] files = ftpclient.listfiles(remote); 
 
    if (files.length != 1) 
    { 
      log.getlogger(this.getclass()).info("远程文件不唯一"); 
      return ftpstatus.file_not_unique; 
    } 
 
    long lremotesize = files[0].getsize(); 
 
    if (f.exists()) 
    { 
      outputstream out = new fileoutputstream(f, true); 
      log.getlogger(this.getclass()).info("本地文件大小为:" + f.length()); 
 
      if (f.length() >= lremotesize) 
      { 
 
        log.getlogger(this.getclass()).info("本地文件大小大于远程文件大小,下载中止"); 
        return ftpstatus.remote_smaller_local; 
 
      } 
 
      ftpclient.setrestartoffset(f.length()); 
 
      boolean status = ftpclient.retrievefile(remote, out); 
      result=status?ftpstatus.download_from_break_success:ftpstatus.download_from_break_faild; 
      out.close(); 
 
    } else 
    { 
      outputstream out = new fileoutputstream(f); 
      boolean status = ftpclient.retrievefile(remote, out); 
      result=status?ftpstatus.download_from_break_success:ftpstatus.download_from_break_faild; 
      out.close(); 
    } 
 
    return result; 
 
  } 
 
  /** 
   * 
   * 上传文件到ftp服务器,支持断点续传 
   * 
   * @param local 
   *      本地文件名称,绝对路径 
   * 
   * @param remote 
   *      远程文件路径,使用/home/directory1/subdirectory/file.ext 
   *      按照linux上的路径指定方式,支持多级目录嵌套,支持递归创建不存在的目录结构 
   * 
   * @return 上传结果 
   * 
   * @throws ioexception 
   */ 
 
  @suppresswarnings("resource") 
  public ftpstatus upload(string local, string remote) throws ioexception 
  { 
    // 设置passivemode传输 
    ftpclient.enterlocalpassivemode(); 
 
    // 设置以二进制流的方式传输 
    ftpclient.setfiletype(ftp.binary_file_type); 
 
    ftpstatus result; 
 
    // 对远程目录的处理 
    string remotefilename = remote; 
 
    if (remote.contains("/")) 
    { 
 
      remotefilename = remote.substring(remote.lastindexof("/") + 1); 
 
      string directory = remote.substring(0, remote.lastindexof("/") + 1); 
 
      if (!directory.equalsignorecase("/") && !ftpclient.changeworkingdirectory(directory)) 
      { 
 
        // 如果远程目录不存在,则递归创建远程服务器目录 
 
        int start = 0; 
 
        int end = 0; 
 
        if (directory.startswith("/")) 
        { 
 
          start = 1; 
 
        } else 
        { 
 
          start = 0; 
 
        } 
 
        end = directory.indexof("/", start); 
 
        while (true) 
        { 
 
          string subdirectory = remote.substring(start, end); 
 
          if (!ftpclient.changeworkingdirectory(subdirectory)) 
          { 
 
            if (ftpclient.makedirectory(subdirectory)) 
            { 
 
              ftpclient.changeworkingdirectory(subdirectory); 
 
            } else 
            { 
 
              log.getlogger(this.getclass()).info("创建目录失败"); 
 
              return ftpstatus.create_directory_fail; 
 
            } 
 
          } 
 
          start = end + 1; 
 
          end = directory.indexof("/", start); 
 
          // 检查所有目录是否创建完毕 
 
          if (end <= start) 
          { 
 
            break; 
 
          } 
 
        } 
 
      } 
 
    } 
 
    // 检查远程是否存在文件 
 
    ftpfile[] files = ftpclient.listfiles(remotefilename); 
 
    if (files.length == 1) 
    { 
 
      long remotesize = files[0].getsize(); 
 
      file f = new file(local); 
 
      long localsize = f.length(); 
 
      if (remotesize == localsize) 
      { 
 
        return ftpstatus.file_exits; 
 
      } else if (remotesize > localsize) 
      { 
 
        return ftpstatus.remote_bigger_local; 
 
      } 
 
      // 尝试移动文件内读取指针,实现断点续传 
 
      inputstream is = new fileinputstream(f); 
 
      if (is.skip(remotesize) == remotesize) 
      { 
 
        ftpclient.setrestartoffset(remotesize); 
 
        if (ftpclient.storefile(remote, is)) 
        { 
 
          return ftpstatus.upload_from_break_success; 
 
        } 
 
      } 
 
      // 如果断点续传没有成功,则删除服务器上文件,重新上传 
 
      if (!ftpclient.deletefile(remotefilename)) 
      { 
 
        return ftpstatus.delete_remote_faild; 
 
      } 
 
      is = new fileinputstream(f); 
 
      if (ftpclient.storefile(remote, is)) 
      { 
 
        result = ftpstatus.upload_new_file_success; 
 
      } else 
      { 
 
        result = ftpstatus.upload_new_file_failed; 
 
      } 
 
      is.close(); 
 
    } else 
    { 
 
      inputstream is = new fileinputstream(local); 
 
      if (ftpclient.storefile(remotefilename, is)) 
      { 
 
        result = ftpstatus.upload_new_file_success; 
 
      } else 
      { 
 
        result = ftpstatus.upload_new_file_failed; 
 
      } 
 
      is.close(); 
    } 
 
    return result; 
 
  } 
 
  /** 
   * 
   * 断开与远程服务器的连接 
   * 
   * @throws ioexception 
   */ 
 
  public void disconnect() throws ioexception 
  { 
 
    if (ftpclient.isconnected()) 
    { 
      ftpclient.disconnect(); 
    } 
 
  } 
 
  public static void main(string[] args) 
  { 
    ftputils myftp = new ftputils(); 
    try 
    { 
 
      myftp.connect("192.168.1.200", 21, "duser", "htpduserxp32"); 
 
      log.getlogger(ftputils.class).info(myftp.upload("c:\\users\\administrator\\desktop\\swing.drawer.jar", "/jars/swing.drawer.jar")); 
 
      myftp.disconnect(); 
 
    } catch (ioexception e) 
    { 
 
      log.getlogger(ftputils.class).info("ftp上传文件异常:" + e.getmessage()); 
 
    } 
 
  } 
 
} 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网