服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

一个简单的ftp客户端实现

import java.io.bufferedinputstream;
import java.io.bufferedoutputstream;
import java.io.bufferedreader;
import java.io.bufferedwriter;
import java.io.file;
import java.io.fileinputstream;
import java.io.ioexception;
import java.io.inputstream;
import java.io.inputstreamreader;
import java.io.outputstreamwriter;
import java.net.socket;
import java.util.stringtokenizer;

/**
 * simpleftp is a simple package that implements a java ftp client. with
 * simpleftp, you can connect to an ftp server and upload multiple files.
 <p>
 * copyright paul mutton, <a
 * href="http://www.jibble.org/">http://www.jibble.org/ </a>
 *  
 */
public class simpleftp {

  /**
   * create an instance of simpleftp.
   */
  public simpleftp() {

  }

  /**
   * connects to the default port of an ftp server and logs in as
   * anonymous/anonymous.
   */
  public synchronized void connect(string hostthrows ioexception {
    connect(host, 21);
  }

  /**
   * connects to an ftp server and logs in as anonymous/anonymous.
   */
  public synchronized void connect(string host, int portthrows ioexception {
    connect(host, port, "anonymous""anonymous");
  }

  /**
   * connects to an ftp server and logs in with the supplied username and* password.
   */
  public synchronized void connect(string host, int port, string user,
      string passthrows ioexception {
    if (socket != null) {
      throw new ioexception("simpleftp is already connected. disconnect first.");
    }
    socket = new socket(host, port);
    reader = new bufferedreader(new inputstreamreader(socket.getinputstream()));
    writer = new bufferedwriter(
        new outputstreamwriter(socket.getoutputstream()));

    string response = readline();
    if (!response.startswith("220 ")) {
      throw new ioexception(
          "simpleftp received an unknown response when connecting to the ftp server: "
              + response);
    }

    sendline("user " + user);

    response = readline();
    if (!response.startswith("331 ")) {
      throw new ioexception(
          "simpleftp received an unknown response after sending the user: "
              + response);
    }

    sendline("pass " + pass);

    response = readline();
    if (!response.startswith("230 ")) {
      throw new ioexception(
          "simpleftp was unable to log in with the supplied password: "
              + response);
    }

    // now logged in.
  }

  /**
   * disconnects from the ftp server.
   */
  public synchronized void disconnect() throws ioexception {
    try {
      sendline("quit");
    finally {
      socket = null;
    }
  }

  /**
   * returns the working directory of the ftp server it is connected to.
   */
  public synchronized string pwd() throws ioexception {
    sendline("pwd");
    string dir = null;
    string response = readline();
    if (response.startswith("257 ")) {
      int firstquote = response.indexof('/"');
      int secondquote = response.indexof('/"', firstquote + 1);
      if (secondquote > 0) {
        dir = response.substring(firstquote + 1, secondquote);
      }
    }
    return dir;
  }

  /**
   * changes the working directory (like cd). returns true if successful.
   */
  public synchronized boolean cwd(string dirthrows ioexception {
    sendline("cwd " + dir);
    string response = readline();
    return (response.startswith("250 "));
  }

  /**
   * sends a file to be stored on the ftp server. returns true if the file
   * transfer was successful. the file is sent in passive mode to avoid nat or
   * firewall problems at the client end.
   */
  public synchronized boolean stor(file filethrows ioexception {
    if (file.isdirectory()) {
      throw new ioexception("simpleftp cannot upload a directory.");
    }

    string filename = file.getname();

    return stor(new fileinputstream(file), filename);
  }

  /**
   * sends a file to be stored on the ftp server. returns true if the file
   * transfer was successful. the file is sent in passive mode to avoid nat or
   * firewall problems at the client end.
   */
  public synchronized boolean stor(inputstream inputstream, string filename)
      throws ioexception {

    bufferedinputstream input = new bufferedinputstream(inputstream);

    sendline("pasv");
    string response = readline();
    if (!response.startswith("227 ")) {
      throw new ioexception("simpleftp could not request passive mode: "
          + response);
    }

    string ip = null;
    int port = -1;
    int opening = response.indexof('(');
    int closing = response.indexof(')', opening + 1);
    if (closing > 0) {
      string datalink = response.substring(opening + 1, closing);
      stringtokenizer tokenizer = new stringtokenizer(datalink, ",");
      try {
        ip = tokenizer.nexttoken() "." + tokenizer.nexttoken() "."
            + tokenizer.nexttoken() "." + tokenizer.nexttoken();
        port = integer.parseint(tokenizer.nexttoken()) 256
            + integer.parseint(tokenizer.nexttoken());
      catch (exception e) {
        throw new ioexception("simpleftp received bad data link information: "
            + response);
      }
    }

    sendline("stor " + filename);

    socket datasocket = new socket(ip, port);

    response = readline();
    if (!response.startswith("150 ")) {
      throw new ioexception("simpleftp was not allowed to send the file: "
          + response);
    }

    bufferedoutputstream output = new bufferedoutputstream(datasocket
        .getoutputstream());
    byte[] buffer = new byte[4096];
    int bytesread = 0;
    while ((bytesread = input.read(buffer)) != -1) {
      output.write(buffer, 0, bytesread);
    }
    output.flush();
    output.close();
    input.close();

    response = readline();
    return response.startswith("226 ");
  }

  /**
   * enter binary mode for sending binary files.
   */
  public synchronized boolean bin() throws ioexception {
    sendline("type i");
    string response = readline();
    return (response.startswith("200 "));
  }

  /**
   * enter ascii mode for sending text files. this is usually the default mode.
   * make sure you use binary mode if you are sending images or other binary
   * data, as ascii mode is likely to corrupt them.
   */
  public synchronized boolean ascii() throws ioexception {
    sendline("type a");
    string response = readline();
    return (response.startswith("200 "));
  }

  /**
   * sends a raw command to the ftp server.
   */
  private void sendline(string linethrows ioexception {
    if (socket == null) {
      throw new ioexception("simpleftp is not connected.");
    }
    try {
      writer.write(line + "/r/n");
      writer.flush();
      if (debug) {
        system.out.println("> " + line);
      }
    catch (ioexception e) {
      socket = null;
      throw e;
    }
  }

  private string readline() throws ioexception {
    string line = reader.readline();
    if (debug) {
      system.out.println("< " + line);
    }
    return line;
  }

  private socket socket = null;

  private bufferedreader reader = null;

  private bufferedwriter writer = null;

  private static boolean debug = false;

}

扫描关注微信公众号