欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java使用FTPClient类读写FTP

程序员文章站 2024-02-28 23:28:46
本文实例为大家分享了java使用ftpclient类读写ftp的具体代码,供大家参考,具体内容如下 1.首先先导入相关jar包 2.创建一个连接ftp的工具类ftp...

本文实例为大家分享了java使用ftpclient类读写ftp的具体代码,供大家参考,具体内容如下

1.首先先导入相关jar包

Java使用FTPClient类读写FTP

2.创建一个连接ftp的工具类ftputil.java

package com.metarnet.ftp.util; 
 
import java.io.ioexception; 
import java.io.inputstream; 
import java.net.socketexception; 
import java.util.properties; 
 
import org.apache.commons.net.ftp.ftpclient; 
import org.apache.commons.net.ftp.ftpreply; 
import org.apache.log4j.logger; 
 
public class ftputil { 
  private static logger logger = logger.getlogger(ftputil.class); 
 
   
   
  /** 
   * 获取ftpclient对象 
   * @param ftphost ftp主机服务器 
   * @param ftppassword ftp 登录密码 
   * @param ftpusername ftp登录用户名 
   * @param ftpport ftp端口 默认为21 
   * @return 
   */ 
  public static ftpclient getftpclient(string ftphost, string ftppassword, 
      string ftpusername, int ftpport) { 
    ftpclient ftpclient = null; 
    try { 
      ftpclient = new ftpclient(); 
      ftpclient.connect(ftphost, ftpport);// 连接ftp服务器 
      ftpclient.login(ftpusername, ftppassword);// 登陆ftp服务器 
      if (!ftpreply.ispositivecompletion(ftpclient.getreplycode())) { 
        logger.info("未连接到ftp,用户名或密码错误。"); 
        ftpclient.disconnect(); 
      } else { 
        logger.info("ftp连接成功。"); 
      } 
    } catch (socketexception e) { 
      e.printstacktrace(); 
      logger.info("ftp的ip地址可能错误,请正确配置。"); 
    } catch (ioexception e) { 
      e.printstacktrace(); 
      logger.info("ftp的端口错误,请正确配置。"); 
    } 
    return ftpclient; 
  } 
} 

3.编写一个读取ftp上文件的类readftpfile.java

package com.metarnet.ftp.read; 
 
import java.io.bufferedreader; 
import java.io.fileinputstream; 
import java.io.filenotfoundexception; 
import java.io.ioexception; 
import java.io.inputstream; 
import java.io.inputstreamreader; 
import java.net.socketexception; 
 
import org.apache.commons.net.ftp.ftpclient; 
import org.apache.log4j.logger; 
 
import com.metarnet.ftp.util.ftputil; 
 
public class readftpfile { 
  private logger logger = logger.getlogger(readftpfile.class); 
 
  /** 
   * 去 服务器的ftp路径下上读取文件 
   * 
   * @param ftpusername 
   * @param ftppassword 
   * @param ftppath 
   * @param ftpserver 
   * @return 
   */ 
  public string readconfigfileforftp(string ftpusername, string ftppassword, 
      string ftppath, string ftphost, int ftpport, string filename) { 
    stringbuffer resultbuffer = new stringbuffer(); 
    fileinputstream infile = null; 
    inputstream in = null; 
    ftpclient ftpclient = null; 
    logger.info("开始读取绝对路径" + ftppath + "文件!"); 
    try { 
      ftpclient = ftputil.getftpclient(ftphost, ftppassword, ftpusername, 
          ftpport); 
      ftpclient.setcontrolencoding("utf-8"); // 中文支持 
      ftpclient.setfiletype(ftpclient.binary_file_type); 
      ftpclient.enterlocalpassivemode(); 
      ftpclient.changeworkingdirectory(ftppath); 
      in = ftpclient.retrievefilestream(filename); 
    } catch (filenotfoundexception e) { 
      logger.error("没有找到" + ftppath + "文件"); 
      e.printstacktrace(); 
      return "下载配置文件失败,请联系管理员."; 
    } catch (socketexception e) { 
      logger.error("连接ftp失败."); 
      e.printstacktrace(); 
    } catch (ioexception e) { 
      e.printstacktrace(); 
      logger.error("文件读取错误。"); 
      e.printstacktrace(); 
      return "配置文件读取失败,请联系管理员."; 
    } 
    if (in != null) { 
      bufferedreader br = new bufferedreader(new inputstreamreader(in)); 
      string data = null; 
      try { 
        while ((data = br.readline()) != null) { 
          resultbuffer.append(data + "\n"); 
        } 
      } catch (ioexception e) { 
        logger.error("文件读取错误。"); 
        e.printstacktrace(); 
        return "配置文件读取失败,请联系管理员."; 
      }finally{ 
        try { 
          ftpclient.disconnect(); 
        } catch (ioexception e) { 
          e.printstacktrace(); 
        } 
      } 
    }else{ 
      logger.error("in为空,不能读取。"); 
      return "配置文件读取失败,请联系管理员."; 
    } 
    return resultbuffer.tostring(); 
  } 
} 

4.创建一个往ftp上写入文件的类writeftpfile.java

package com.metarnet.ftp.write; 
 
import java.io.bufferedwriter; 
import java.io.file; 
import java.io.fileinputstream; 
import java.io.filewriter; 
import java.io.ioexception; 
import java.io.inputstream; 
 
import org.apache.commons.net.ftp.ftpclient; 
import org.apache.commons.net.ftp.ftpfile; 
import org.apache.log4j.logger; 
 
import com.metarnet.ftp.util.ftputil; 
 
public class writeftpfile { 
 
  private logger logger = logger.getlogger(writeftpfile.class); 
 
  /** 
   * 本地上传文件到ftp服务器 
   * 
   * @param ftppath 
   *      远程文件路径ftp 
   * @throws ioexception 
   */ 
  public void upload(string ftppath, string ftpusername, string ftppassword, 
      string ftphost, int ftpport, string filecontent, 
      string writetempfielpath) { 
    ftpclient ftpclient = null; 
    logger.info("开始上传文件到ftp."); 
    try { 
      ftpclient = ftputil.getftpclient(ftphost, ftppassword, 
          ftpusername, ftpport); 
      // 设置passivemode传输 
      ftpclient.enterlocalpassivemode(); 
      // 设置以二进制流的方式传输 
      ftpclient.setfiletype(ftpclient.binary_file_type); 
      // 对远程目录的处理 
      string remotefilename = ftppath; 
      if (ftppath.contains("/")) { 
        remotefilename = ftppath 
            .substring(ftppath.lastindexof("/") + 1); 
      } 
      // ftpfile[] files = ftpclient.listfiles(new 
      // string(remotefilename)); 
      // 先把文件写在本地。在上传到ftp上最后在删除 
      boolean writeresult = write(remotefilename, filecontent, 
          writetempfielpath); 
      if (writeresult) { 
        file f = new file(writetempfielpath + "/" + remotefilename); 
        inputstream in = new fileinputstream(f); 
        ftpclient.storefile(remotefilename, in); 
        in.close(); 
        logger.info("上传文件" + remotefilename + "到ftp成功!"); 
        f.delete(); 
      } else { 
        logger.info("写文件失败!"); 
      } 
    } catch (exception e) { 
      e.printstacktrace(); 
    }finally{ 
      try { 
        ftpclient.disconnect(); 
      } catch (ioexception e) { 
        e.printstacktrace(); 
      } 
    } 
  } 
 
  /** 
   * 把配置文件先写到本地的一个文件中取 
   * 
   * @param ftppath 
   * @param str 
   * @return 
   */ 
  public boolean write(string filename, string filecontext, 
      string writetempfielpath) { 
    try { 
      logger.info("开始写配置文件"); 
      file f = new file(writetempfielpath + "/" + filename); 
      if(!f.exists()){ 
        if(!f.createnewfile()){ 
          logger.info("文件不存在,创建失败!"); 
        } 
      } 
      bufferedwriter bw = new bufferedwriter(new filewriter(f, true)); 
      bw.write(filecontext.replaceall("\n", "\r\n")); 
      bw.flush(); 
      bw.close(); 
      return true; 
    } catch (exception e) { 
      logger.error("写文件没有成功"); 
      e.printstacktrace(); 
      return false; 
    } 
  } 
} 

5.建立一个测试类ftpmain.java

package com.metarnet.ftp.main; 
 
import java.io.inputstream; 
import java.util.properties; 
 
import org.apache.log4j.logger; 
 
import com.metarnet.ftp.read.readftpfile; 
import com.metarnet.ftp.util.ftputil; 
import com.metarnet.ftp.write.writeftpfile; 
 
public class ftpmain { 
   
  private static logger logger = logger.getlogger(ftpmain.class); 
 
  public static void main(string[] args) { 
    int ftpport = 0; 
    string ftpusername = ""; 
    string ftppassword = ""; 
    string ftphost = ""; 
    string ftppath = ""; 
    string writetempfielpath = ""; 
    try { 
      inputstream in = ftputil.class.getclassloader() 
          .getresourceasstream("env.properties"); 
      if (in == null) { 
        logger.info("配置文件env.properties读取失败"); 
      } else { 
        properties properties = new properties(); 
        properties.load(in); 
        ftpusername = properties.getproperty("ftpusername"); 
        ftppassword = properties.getproperty("ftppassword"); 
        ftphost = properties.getproperty("ftphost"); 
        ftpport = integer.valueof(properties.getproperty("ftpport")) 
            .intvalue(); 
        ftppath = properties.getproperty("ftppath"); 
        writetempfielpath = properties.getproperty("writetempfielpath"); 
         
        readftpfile read = new readftpfile(); 
        string result = read.readconfigfileforftp(ftpusername, ftppassword, ftppath, ftphost, ftpport, "huawei_220.248.192.200.cfg"); 
        system.out.println("读取配置文件结果为:" + result); 
         
        writeftpfile write = new writeftpfile(); 
        ftppath = ftppath + "/" + "huawei_220.248.192.200_new1.cfg"; 
        write.upload(ftppath, ftpusername, ftppassword, ftphost, ftpport, result, writetempfielpath); 
      } 
    } catch (exception e) { 
      e.printstacktrace(); 
    } 
  } 
} 

最后肯定是执行,看最后执行结果,ok步骤已讲完。

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