远程FTP处理Java类

jopen 12年前

项目需要和其他系统实现数据同步(非及时接口),也就是要把该系统产生的数据上传到FTP服务器上,供其他系统下载实现同步。代码如下 :

package com.zte.pp.usermsgsync;    import java.io.File;   import java.io.FileInputStream;   import java.io.FileOutputStream;   import java.io.InputStream;   import java.io.OutputStream;   import java.util.ArrayList;   import java.util.List;     import org.apache.commons.net.ftp.FTPClient;   //import org.apache.commons.net.ftp.FTPClientConfig;   import org.apache.commons.net.ftp.FTPFile;   import org.apache.commons.net.ftp.FTPReply;   import org.apache.log4j.Logger;       /**   * 远程FTP处理类   * <a href="http://my.oschina.net/arthor" class="referer" target="_blank">@author</a>  SU   * @version 1.0,  2012/09/15   */  public class FTPUtil   {     private Logger logger = Logger.getLogger(FTPUtil.class);    private String ip ;    private int port;    private String pwd;    private String user;    private FTPClient ftpClient;      private FTPUtil()   {    }   public FTPUtil(String ip, int port, String user, String pwd)   {        this.ip = ip;    this.port = port;    this.user = user;    this.pwd = pwd;    }      /**    * 连接远程FTP服务器    * @param ip ip地址    * @param port 端口号    * @param user 用户名    * @param pwd 密码    * <a href="http://my.oschina.net/u/556800" class="referer" target="_blank">@return</a>     * @throws Exception    */    public boolean connectServer(String ip, int port, String user, String pwd) throws Exception    {      boolean isSuccess = false;    try     {     ftpClient = new FTPClient();     ftpClient.connect(ip, port);     ftpClient.setControlEncoding("GBK");  //      FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT); //此类commons-net-2.0不提供  //      conf.setServerLanguageCode("zh");     ftpClient.login(user, pwd);     ftpClient.setFileType(FTPClient.ASCII_FILE_TYPE);     if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode()))      {      isSuccess = true;      System.out.println("--连接ftp服务器成功!!!");     }     else      {      ftpClient.disconnect();      logger.error("连不上ftp服务器!");  //    throw new BossOperException();     }    }     catch (Exception e)     {     logger.error("连接FTP服务器异常..", e);     e.printStackTrace();    }      return isSuccess;   }         /**    * 远程FTP上传文件    * @param remotePath    * @param localPath    * @param files    * <a href="http://my.oschina.net/u/556800" class="referer" target="_blank">@return</a>     * @throws Exception    */   public File uploadFile(String remotePath, List<File> files)throws Exception {    File fileIn = null;    OutputStream os = null;    FileInputStream is = null;    try     {     for (File file : files)      {      if (connectServer(this.getIp(), this.getPort(), this.getUser(),this.getPwd()))       {       System.out.println("----进入文件上传到FTP服务器--->");       ftpClient.changeWorkingDirectory(remotePath);       os = ftpClient.storeFileStream(file.getName());       fileIn = file;       is = new FileInputStream(fileIn);       byte[] bytes = new byte[1024];       int c;       while ((c = is.read(bytes)) != -1)       {        os.write(bytes, 0, c);       }      }     }    }     catch (Exception e)     {     logger.error("上传FTP文件异常: ", e);    }     finally    {     os.close();     is.close();     ftpClient.logout();     if (ftpClient.isConnected())     {      ftpClient.disconnect();     }    }      return fileIn;   }          /**     * 远程FTP上删除一个文件     * @param remotefilename     * <a href="http://my.oschina.net/u/556800" class="referer" target="_blank">@return</a>      */      public boolean deleteFile(String remotefilename)      {        boolean flag = true;        try       {         if (connectServer(this.getIp(), this.getPort(), this.getUser(),this.getPwd()))         {         flag = ftpClient.deleteFile(remotefilename);          if (flag)          {           System.out.println("远程删除FTP文件成功!");          }         else         {           System.out.println("-----远程删除FTP文件失败!----");          }         }       }       catch (Exception ex)       {         logger.error("远程删除FTP文件异常: ", ex);        ex.printStackTrace();        }        return flag;       }              /**    * 远程FTP删除目录下的所有文件    * @param remotePath    * @param localPath    * <a href="http://my.oschina.net/u/556800" class="referer" target="_blank">@return</a>     * @throws Exception    */   public void deleteAllFile(String remotePath, String localPath) throws Exception    {    try     {     if (connectServer(this.getIp(), this.getPort(), this.getUser(),this.getPwd()))      {      ftpClient.changeWorkingDirectory(remotePath);      FTPFile[] ftpFiles = ftpClient.listFiles();      for (FTPFile file : ftpFiles)       {       ftpClient.deleteFile(file.getName());             }     }    }     catch (Exception e)     {     logger.error("从FTP服务器删除文件异常:", e);     e.printStackTrace();    }     finally     {     ftpClient.logout();     if (ftpClient.isConnected())     {      ftpClient.disconnect();     }    }   }         /**     * 远程FTP上创建目录     * @param dir     * <a href="http://my.oschina.net/u/556800" class="referer" target="_blank">@return</a>      */      public boolean makeDirectory(String dir)      {        boolean flag = true;        try       {         if (connectServer(this.getIp(), this.getPort(), this.getUser(),this.getPwd()))         {         flag = ftpClient.makeDirectory(dir);          if (flag)          {           System.out.println("make Directory " + dir + " succeed");          }         else         {              System.out.println("make Directory " + dir + " false");          }         }       }       catch (Exception ex)       {         logger.error("远程FTP生成目录异常:", ex);        ex.printStackTrace();        }        return flag;       }              /**    * 远程FTP下载文件    *     * @param remotePath    * @param localPath    * <a href="http://my.oschina.net/u/556800" class="referer" target="_blank">@return</a>     * @throws Exception    */   public List<File> downloadFile(String remotePath, String localPath ) throws Exception    {    List<File> result = new ArrayList<File>();    File fileOut = null;    InputStream is = null;    FileOutputStream os = null;    try     {     if (connectServer(this.getIp(), this.getPort(), this.getUser(),this.getPwd()))      {      ftpClient.changeWorkingDirectory(remotePath);      FTPFile[] ftpFiles = ftpClient.listFiles();        for (FTPFile file : ftpFiles)       {       is = ftpClient.retrieveFileStream(file.getName());       if (localPath != null && !localPath.endsWith(File.separator))        {        localPath = localPath + File.separator;        File path = new File(localPath);        if (!path.exists())         {         path.mkdirs();        }       }       fileOut = new File(localPath + file.getName());       os = new FileOutputStream(fileOut);       byte[] bytes = new byte[1024];       int c;       while ((c = is.read(bytes)) != -1)        {        os.write(bytes, 0, c);       }         result.add(fileOut);       ftpClient.completePendingCommand();       os.flush();       is.close();       os.close();      }        for (FTPFile file : ftpFiles)       {       ftpClient.deleteFile(file.getName());      }     }    }     catch (Exception e)     {     logger.error("从FTP服务器下载文件异常:", e);     e.printStackTrace();    }     finally     {     ftpClient.logout();     if (ftpClient.isConnected())     {      ftpClient.disconnect();     }    }      return result;   }              public String getIp() {    return ip;   }     public void setIp(String ip) {    this.ip = ip;   }     public int getPort() {    return port;   }     public void setPort(int port) {    this.port = port;   }     public String getPwd() {    return pwd;   }     public void setPwd(String pwd) {    this.pwd = pwd;   }     public String getUser() {    return user;   }     public void setUser(String user) {    this.user = user;   }        /**    * 测试方法    * @param args    */   public static void main(String[] args)   {    String ip = "10.123.148.88";    int port = 21 ;     String user ="root";       String pwd ="root"  ;       String remotePath = "//home//V010//01//000011//" ;        //上传文件配置  //  List<File> fileList = new ArrayList<File>();  ////  File onefile = new File("F:\\V010\\01\\000011\\RSP\\0100001120120701122712_Day.txt");  //  File onefile = new File("F:\\V010\\01\\000011\\RSP\\" ,"01000011201209263112839_Day.txt");  //  System.out.println("----本地文件路径--->"+ onefile.getAbsolutePath());  //  fileList.add(onefile);        FTPUtil ftpupload = new FTPUtil(ip,port,user,pwd);    try     {  //   ftpupload.uploadFile(remotePath, fileList);  //测试上传文件          //删除文件  //   String remotefilename = remotePath+"01000011201209263112839_Day.txt";  //   System.out.println("----远程FTF上的文件名----"+remotefilename);  //   ftpupload.deleteFile(remotefilename);             //下载目录下所有的文件     String localPath = "F:\\TEST\\" ;  //   ftpupload.downloadFile(remotePath, localPath);               ftpupload.deleteAllFile(remotePath, localPath);         }    catch (Exception e)     {     e.printStackTrace();    }   }    }