用Java实现FTP上传

为了解决AMQ取消fileserver的问题,今天研究了一下源码,把AMQ里的ftp上传方法提取出来,单独写成一个类,供以后使用。
需注意的是,需要引用commons.net包,可以直接百度找到,我用的是commons-net-3.5。

package ftpTest;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ConnectException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.jms.JMSException;
import org.apache.commons.net.ftp.FTPClient;

public class FTPStrategy
{
  protected URL url;
  protected String ftpUser = "";
  protected String ftpPass = "";

  public FTPStrategy() throws MalformedURLException {
    this.url = new URL("ftp://sysop:[email protected]/opt/activemq/patches/");
  }

  protected void setUserInformation(String userInfo) {
    if (userInfo != null) {
      String[] userPass = userInfo.split(":");
      if (userPass.length > 0) this.ftpUser = userPass[0];
      if (userPass.length > 1) this.ftpPass = userPass[1]; 
    }
    else { this.ftpUser = "anonymous";
      this.ftpPass = "anonymous"; }
  }

  protected FTPClient createFTP() throws IOException, JMSException
  {
    String connectUrl = this.url.getHost();
    setUserInformation(this.url.getUserInfo());
    int port = this.url.getPort() < 1 ? 21 : this.url.getPort();
    
    FTPClient ftp = new FTPClient();
    try {
      ftp.connect(connectUrl, port);
    } catch (ConnectException e) {
      throw new JMSException("Problem connecting the FTP-server");
    }
    if (!ftp.login(this.ftpUser, this.ftpPass)) {
      ftp.quit();
      ftp.disconnect();
      throw new JMSException("Cant Authentificate to FTP-Server");
    }
    return ftp;
  }
  public URL uploadFile(File file) throws JMSException, IOException  {
   FTPClient ftp = createFTP();
   try {
     String path = this.url.getPath();
     String workingDir = path.substring(0, path.lastIndexOf("/"));
     String filename = file.getName();
     ftp.setFileType(2);
     String url;
     if (!ftp.changeWorkingDirectory(workingDir))
       url = this.url.toString().replaceFirst(this.url.getPath(), "") + "/";
     else {
       url = this.url.toString();
     }
     InputStream in = new FileInputStream(file);
     if (!ftp.storeFile(filename, in)) {
       throw new JMSException("FTP store failed: " + ftp.getReplyString());
     }
     return new URL(url + filename);
   } finally {
     ftp.quit();
     ftp.disconnect();
   }
  }
}

直接实例化后,使用uploadFile方法就可以直接发文件了

public static void main (String[] args) throws JMSException, IOException {
 FTPStrategy ftps = new FTPStrategy();
 ftps.uploadFile(new File("e:\\test.vbs"));
}

源码读来真是获益良多,虽然常会被一个个类弄昏头,但是整体考虑时又能发现设计的巧妙。

你可能感兴趣的:(用Java实现FTP上传)